仅替换链接内部的字符串


Replace string only inside of a link

我有一个这样的字符串:

<a href="blabla/test/city">city</a>

我只想删除实际链接中最后一次出现的/城市,我会有这个:

<a href="blabla/test">city</a>

我不能只是替换,因为我不想替换浏览器中显示的城市。

我已经开始做一些事情:

$x = '<a href="test/gothenburg">gothenburg</a>';    
$pos = strrpos($x, '">');
$x = substr($x, 0, $pos);                        
echo $x;

如何安全地完成此替换?

您可以使用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>

示例:

http://regex101.com/r/gZ7aG9

要在被替换单词之前保留/,可以使用模式:('w+)(?=["])

<?php
$x = '<a href="test/gothenburg">gothenburg</a>';  
$pattern = '/'w+">/'; 
$y = preg_replace($pattern, '">', $x);
echo $y;
?>
strreplace(Href="blabla/test/city", href="blabla/test")

使用真正的str替换课程

使用preg_matchpreg_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>