PHP将字符串查找为HTML文本并替换它

时间:2011-05-05 15:33:32

标签: php regex

    $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#string,并替换为<a href='mylink.php?myid'>myid</a>

我该怎么办?

2 个答案:

答案 0 :(得分:4)

为什么需要正则表达式来执行此操作,或者您是否计划替换所有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);

答案 1 :(得分:3)

$text = preg_replace("/\#(\d+?)\#/s" , "<a href=\"mylink.php?$1\">$1</a>" , $text);
相关问题