我有一个这样的字符串:
<a href="blabla/test/city">city</a>
我想只删除实际链接中最后一次出现的/ city,我将会这样:
<a href="blabla/test">city</a>
我不能只做替换因为我不想替换浏览器中显示的城市。
我开始做点什么了:
$x = '<a href="test/gothenburg">gothenburg</a>';
$pos = strrpos($x, '">');
$x = substr($x, 0, $pos);
echo $x;
如何安全地完成此替换?
答案 0 :(得分:1)
您可以使用preg_replace
:
$searchText = '<a href="blabla/test/city">city</a>';
$result = preg_replace("/(\/\w+)(?=[\"])/u", "", $searchText);
print_r($result);
输出:
<a href="blabla/test">city</a>
示例:
要在替换后的单词前留下/
,您可以使用模式:(\w+)(?=["])
答案 1 :(得分:0)
strreplace(Href="blabla/test/city", href="blabla/test")
使用真正的str替换课程
答案 2 :(得分:0)
<?php
$x = '<a href="test/gothenburg">gothenburg</a>';
$pattern = '/\w+">/';
$y = preg_replace($pattern, '">', $x);
echo $y;
?>
答案 3 :(得分:0)
使用preg_match
和preg_replace
找到解决方案,找出<a href="…"></a>
标记之间的城市名称,然后找到href
并删除最后一部分包含城市名称的URL:
// Set the city link HTML.
$city_link_html = '<a href="test/gothenburg/">gothenburg</a>';
// Run a regex to get the value between the link tags.
preg_match('/(?<=>).*?(?=<\/a>)/is', $city_link_html, $city_matches);
// Run the preg match all command with the regex pattern.
preg_match('/(?<=href=")[^\s"]+/is', $city_link_html, $city_url_matches);
// Set the new city URL by removing only the the matched city from the URL.
$new_city_url = preg_replace('#' . $city_matches[0] . '?/$#', '', $city_url_matches[0]);
// Replace the old city URL in the string with the new city URL.
$city_link_html = preg_replace('#' . $city_url_matches[0] . '#', $new_city_url, $city_link_html);
// Echo the results with 'htmlentities' so the results can be read in a browser.
echo htmlentities($city_link_html);
最终结果是:
<a href="test/">gothenburg</a>