用逗号替换字符串或用 preg_replace 不替换字符串

发布于 2025-01-07 02:47:00 字数 570 浏览 1 评论 0原文

我有一个具有以下值格式的字符串:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";

$str = "Computer";

如何使用 preg_replace 将其转换为:

$str = "<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, 
<a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>,  <a href='p.php?s=50k'>50k</a>";

$str = "<a href='p.php?s=Computer'>Computer</a>";

I have a string with this value format:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";

or

$str = "Computer";

How can I convert it with preg_replace to:

$str = "<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, 
<a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>,  <a href='p.php?s=50k'>50k</a>";

$str = "<a href='p.php?s=Computer'>Computer</a>";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城挽邺 2025-01-14 02:47:00
$str = preg_replace('/([\w-]+)/', '<a href=\'p.php?s=$1\'>$1</a>', $str);
$str = preg_replace('/([\w-]+)/', '<a href=\'p.php?s=$1\'>$1</a>', $str);
蓝颜夕 2025-01-14 02:47:00

尝试一下:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";
$str = preg_replace('/([^,\s]+)/', "<a href='p.php?s=$1'>$1</a>", $str);
echo $str,"\n";

输出:

<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, <a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>, <a href='p.php?s=50k'>50k</a>

Have a try with:

$str = "Apple, Orange, Computer-Hardware, preg_replace, 50k";
$str = preg_replace('/([^,\s]+)/', "<a href='p.php?s=$1'>$1</a>", $str);
echo $str,"\n";

output:

<a href='p.php?s=Apple'>Apple</a>, <a href='p.php?s=Orange'>Orange</a>, <a href='p.php?s=Computer-Hardware'>Computer-Hardware</a>, <a href='p.php?s=preg_replace'>preg_replace</a>, <a href='p.php?s=50k'>50k</a>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文