繁体   English   中英

str_replace无法正常使用PHP

[英]str_replace not working as expcted php

str_replace找不到该字符串并按应有的方式进行替换。

这是echo输出的$ data字符串

 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";

编辑

这是$ str之前的$ data

 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

问题出在

$datastart = $datastart -1;

如果$datastart为0(在您的情况下正确,因为eth在字符串的开头),则$datastart -1; 使$datastart等于-1

万一影响$data = substr($data,$datastart); 因为负偏移量会将$data字符串更改为u 在其中绝对没有$pattern

我认为最简单的方法是检查$datastart是否小于0并将其设置为零:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM