作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我通常自己解决 PHP 问题非常有效,但是对于这个特定问题,我似乎找不到可行的解决方案。
我有一个由标准文本组成的 $string,在文本中会有一些关键字被 [方括号] 包围,我想将它们转换为链接,但是将字符串与预定义的数组进行比较并不是一个简单的例子'known' 关键字并进行简单的替换,因为 [方括号] 的内容可以是任何内容。
例如,我需要以下内容:
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=a+gray+sky">A Gray Sky</a> and <a href="search.php?search=sophomore+effort">Sophomore Effort</a>.
最佳答案
$string = "John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].";
function rep_callback($match)
{
$query = substr($match[0],1,-1);
$query = urlencode($query);
$link = '<a href="search.php?search='.$query.'">'.$match[0].'</a>';
return $link;
}
echo $string."\n";
echo preg_replace_callback("/\[.+\]/U", "rep_callback", $string)."\n";
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include [A Gray Sky] and [Sophomore Effort].
John Roberts is a jazz musician from Florida born in 1934. Some of his notable works include <a href="search.php?search=A+Gray+Sky">[A Gray Sky]</a> and <a href="search.php?search=Sophomore+Effort">[Sophomore Effort]</a>.
关于php - 替换字符串中所有出现的任何括号括起来的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10491967/
我是一名优秀的程序员,十分优秀!