繁体   English   中英

PHP在HTML文本中找到字符串并将其替换

[英]PHP find string into HTML text and replace it

    $text = "<p>Pellentesque ac urna eget diam volutpat suscipit
     ac faucibus #8874# quam. Aliquam molestie hendrerit urna, 
    vel condimentum magna venenatis a.<br/> Donec a mattis ante. 
Ut odio odio, ultrices ut faucibus vel, #2514# dapibus sed nunc. In hac sed.</p>";

我需要搜索#myid#字符串,并替换为<a href='mylink.php?myid'>myid</a>

我能怎么做?

为什么需要正则表达式来执行此操作,或者您打算替换所有4位数字(用#包围)?

如果是单个ID,则可以使用:

$replace_id = 2514;

$replacement_find = "#{$replace_id}#";
$replacement_replace = "<a href=\"mylink.php?{$replace_id}\">{$replace_id}</a>";

$text_final = str_replace($replacement_find, $replacement_replace, $text);

如果您要进行多次替换(或根据注释,不知道任何ID),则可以使用以下方法:

$text_final = preg_replace('@#([0-9]+?)#@', '<a href="mylink.php?$1">$1</a>', $text);

编辑:从您的评论,您可以使用preg_match_all获取包含在字符串中的数组中的所有ID。 在下面的代码中, $matches[1]包含正则表达式()中所有内容的值,请参见print_r返回。

preg_match_all('@#([0-9]+?)#@', $text, $matches);
print_r($matches[1]);

为了适应您的最新请求,您可以使用preg_replace_callback来获取所需的信息:

function callback($matches) {
        return '<a href="mylink.php?' . $matches[1] . '>' . getProductName($matches[1]) . '</a>';
}
$text_final = preg_replace_callback('@#([0-9]+?)#@', "callback", $text);
$text = preg_replace("/\#(\d+?)\#/s" , "<a href=\"mylink.php?$1\">$1</a>" , $text);

暂无
暂无

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

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