我需要在描述中放置产品链接。
$myDesc="this is some text about the thing on the page and it
has a match <a href="[1145]">this product</a>
also has another matching <a href="[101145]">product</a>.";
想用一个能够检索正确链接的函数替换产品编号'$ theNumber'......就像这样
$myDesc = preg_replace("/\\[([0-9]+)\\]/", productlink('$1'), $myDesc);
最终结果与此相似
this is some text about the thing on the page and it
has a match <a href="http://www.example.com/this-product-name-1145">this product</a>
also has another matching <a href="http://www.example.com/another-product-name-101145">product</a>.
感谢您的任何见解
答案 0 :(得分:1)
这应该为你做。
语法问题:
在双引号封装的字符串中使用时,需要对双引号进行转义。
正则表达式问题:
你的正则表达式说...找到一个文字[
然后找到任何非数字或括号零次或多次\[[^0-9\]]*\]
。您需要一个括号,任意数字,一次或多次,然后是括号\[([0-9]+)\]
。你没有提供productlink
功能,所以我不知道它做了什么,这是我最好的猜测。
您还需要使用正则引号'~\[([0-9]+)\]~'
。
<?php
$myDesc = 'this is some text about the thing on the page and it
has a match <a href="[1145]">this product</a>
also has another matching <a href="[101145]">product</a>.';
$myDesc = preg_replace_callback('~\[([0-9]+)\]~', "productlink", $myDesc);
echo $myDesc;
function productlink($theNumber) {
//select title from DB
//$title = fetched title
$title = '';
$title = str_replace(' ', '-', $title) . '-';
return 'http://www.example.com/' . $title . $theNumber[1];
}
输出:
this is some text about the thing on the page and it
has a match <a href="http://www.example.com/-1145">this product</a>
also has another matching <a href="http://www.example.com/-101145">product</a>.