如何在preg_replace中回显?

时间:2018-03-25 02:36:31

标签: php preg-replace echo

感觉卡住了。无法在stackoverflow上找到答案。我需要在preg_replace中回显$ subcat和$ cat。它不起作用。有没有办法在preg_replace内回声?

$text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="https://somesite.com/search?cityid=0&lang=en&search=$1&subcatid="'. $subcat .'"&view=ads&catid="'. $cat .'"">#$1</a>', $text);

4 个答案:

答案 0 :(得分:0)

你能尝试这样吗?将这些变量放在大括号{var}

之后
$text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="https://somesite.com/search?cityid=0&lang=en&search=$1&subcatid={$subcat}&view=ads&catid={$cat}">#$1</a>', $text);

$text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="https://somesite.com/search?cityid=0&lang=en&search=$1&subcatid='.$subcat.'&view=ads&catid='.$cat.'">#$1</a>', $text);

答案 1 :(得分:0)

当你不需要时,你将变量用双引号括起来。删除了它。

<强>尝试:

$text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', '<a href="https://somesite.com/search?cityid=0&lang=en&search=$1&subcatid='. $subcat .'&view=ads&catid='. $cat .'">#$1</a>', $text);

答案 2 :(得分:0)

从href中的param值中删除引号,使用"双引号将变量替换为其值,也可以转义$1使其成为文本

   $text = preg_replace('/(?<!\S)#([0-9a-zA-Z]+)/', "<a href='https://somesite.com/search?cityid=0&lang=en&search=\$1&subcatid=$subcat&view=ads&catid=$cat'>#\$1</a>", $text);

答案 3 :(得分:0)

您的模式可以使用i模式修饰符稍微压缩,并通过省略捕获组并使用\K重新启动全字符串匹配来提高效率。此外,您可以使用\\0\$0来表示全字符串匹配(否则将被写入(未转义)为$0或{{1},而不使用点串联来编写替换字符串}})。

代码:(Demo

\0

输出:

$subcat = 1;
$cat = 2;
$text = 'This is a non-qualifying#HashTag and this has white space before it #Test9 and some more text.';
$text = preg_replace('/(?<!\S)#\K[\da-z]+/i', "<a href=\"https://somesite.com/search?cityid=0&lang=en&search=\\0&subcatid=$subcat&view=ads&catid=$cat\">#\\0</a>", $text);
echo $text;