2016-01-23 121 views
0

str_replace沒有找到字符串,而是像它應該那樣替換。str_replace不能正常工作php

這是通過回聲

eth0 192.168.1.1/24 u/u Local eth0.51 192.168.5.1/24 u/u Dev 1 eth1 x.x.x.x/24 u/u Internet eth2 192.168.2.1/24 u/D Local 2 lo 127.0.0.1/8 u/u ::1/128 tun35 192.168.4.222/24 u/u 

這裏輸出的$數據串是我的代碼

$ssh = new Net_SSH2("$routerip"); 
    if (!$ssh->login("$username", "$password")) { 
    return $radioip["error"] ='router error'; 
    } 

$data = $ssh->exec("/opt/vyatta/bin/vyatta-op-cmd-wrapper show interfaces"); 

$string = 'eth'; 

$datastart = strpos($data,$string); 
$datastart = $datastart -1; 

$pattern ='lo 127.0.0.1/8 u/u ::1/128'; 
$replace = ''; 
echo "$pattern"; 
$data = substr($data,$datastart); 
$data = str_replace($pattern,$replace, $data); 
echo "$data"; 

編輯

這是$ SUBSTR

Codes: S - State, L - Link, u - Up, D - Down, A - Admin Down Interface IP Address S/L Description --------- ---------- --- ----------- eth0 192.168.1.1/24 u/u Local eth0.51 192.168.5.1/24 u/u Dev 1 eth1 x.x.x.x/24 u/u Internet eth2 192.168.2.1/24 u/D Local 2 lo 127.0.0.1/8 u/u ::1/128 tun35 192.168.4.222/24 u/u 

回答

0
前數據

問題在於線

$datastart = $datastart -1; 

如果$datastart爲0(如eth是在字符串的開頭是你的情況如此),那麼$datastart -1;使得$datastart等於-1

哪些情況會影響$data = substr($data,$datastart);,因爲負偏移會將$data字符串更改爲僅u。你絕對沒有你的$pattern

我認爲simpliest方式將是檢查是否$datastart小於0,並將其設置爲零:

$datastart = strpos($data,$string); 
if ($datastart < 0) { 
    $datastart = 0; 
} 
+0

請重新審視作爲$數據是 – user1956768

+0

你的代碼工作正常,這些線路的不同 - HTTPS:/ /3v4l.org/so2RL –

+0

它的工作。我正在使用缺少所有額外空格的搜索字符串 – user1956768