str_replace 以 x 开头并以 x 结尾的值
str_replace value which starts with x and end with x
我想使用 str_replace 函数像这样更改许多值;
<p><a href="gogole.com">gogole</a>a ramdom text</p>
到
<p>a ramdom text</p>
或再次
<p><a style="color:red;" href="whosebug.com">Whosebug</a>a ramdom text</p>
到
<p>a ramdom text</p>
那我该怎么做呢?谢谢
由于你要替换的字符串不是完全可以预测的,你需要用到的是正则表达式。对于这种情况,这是一个快速而肮脏的方法,使用 preg_replace():
$string = '<p><a href="gogole.com">gogole</a>a ramdom text</p>';
$stripped = preg_replace("/<a .*?<\/a>/", "", $string);
但是正则表达式可能很棘手,所以要小心。
编辑: 修复评论中建议的表达式。另一种可能是 /<a [^<]*<\/a>/
.
您可以在开始时获得位置:
$start = strpos($myString, "<a ");
结尾如:
$end = strpos($myString, "</a>" + 4);
然后:
$myNewString = substr($myString, 0, $start).substr($myString, $end);
当然,您需要注意边缘情况,例如 <a>
或 </a>
不在字符串中或字符串以 </a>
.
结尾
我想使用 str_replace 函数像这样更改许多值;
<p><a href="gogole.com">gogole</a>a ramdom text</p>
到
<p>a ramdom text</p>
或再次
<p><a style="color:red;" href="whosebug.com">Whosebug</a>a ramdom text</p>
到
<p>a ramdom text</p>
那我该怎么做呢?谢谢
由于你要替换的字符串不是完全可以预测的,你需要用到的是正则表达式。对于这种情况,这是一个快速而肮脏的方法,使用 preg_replace():
$string = '<p><a href="gogole.com">gogole</a>a ramdom text</p>';
$stripped = preg_replace("/<a .*?<\/a>/", "", $string);
但是正则表达式可能很棘手,所以要小心。
编辑: 修复评论中建议的表达式。另一种可能是 /<a [^<]*<\/a>/
.
您可以在开始时获得位置:
$start = strpos($myString, "<a ");
结尾如:
$end = strpos($myString, "</a>" + 4);
然后:
$myNewString = substr($myString, 0, $start).substr($myString, $end);
当然,您需要注意边缘情况,例如 <a>
或 </a>
不在字符串中或字符串以 </a>
.