我正在尝试将用户在存储在 mysql 数据库中的文本框中发布的一些标记解析为链接,类似于 Reddit 和 StackOverflow 的使用风格:
[foo](http://foo.com) = <a href="http://foo.com">foo</a>
到目前为止我已经想出了这个:
if (stristr($text, '[') == TRUE && stristr($text, '](') == TRUE &&
stristr($text, ')') == TRUE && strpos($text, '[') == 0) {
$text = substr($text, 0, strpos($text, ']'));
$href_start = strpos($text, '(');
$href = substr($title, $href_start, strpos($text, ')'));
$text_array = array('[', ']'); $href_array = array('(', ')');
$href = str_replace($href_array, '', $href);
$text_string = str_replace($text_array, '', $text_string);
$text = '<a href="' . $href . '">' . $text_string . '</a>';
}
它有效,但仅当评论以链接开头时有效,而不是当链接出现在文本中间时有效。我还需要从括号中的字符串中抓取一定量的文本作为需要显示的文本标题,所以有时我会这样写最后一个字符串:
$title = '<a href="' . $href . '">' . substr($text, 0, 80) . '</a>';
如果有人能告诉我如何在执行此字符串操作时获取可变数量的文本,那就加分了。我了解 PHP Markdown,但我认为这对于我想做的事情来说有点过分了。
最佳答案
$string = <<<EOS
some text [foo](http://foo.com) and
more text [bar](http://bar.com) and then
a [really looooooooooooooooooooooooooooooooooooooooooooooo00000000000000000ooong description](http://foobar.com)
EOS;
$string = preg_replace_callback(
'~\[([^\]]+)\]\(([^)]+)\)~',
function ($m) {
return '<a href="'.$m[2].'">'.substr($m[1],0,80).'</a>';
},
$string
);
echo $string;
输出:
some text <a href="http://foo.com">foo</a> and
more text <a href="http://bar.com">bar</a> and then
a <a href="http://foobar.com">really looooooooooooooooooooooooooooooooooooooooooooooo00000000000000000ooong de</a>
编辑:
我想你不需要为此使用 preg_replace_callback
- 可以使用 preg_replace
代替,但我更喜欢前者,因为正则表达式更干净一些,您可以对构建链接有更多的控制权。但这是 preg_replace
版本:
$string = preg_replace(
'~\[([^\]]{1,80})[^\]]*\]\(([^)]+)\)~',
'<a href="$2">$1</a>',
$string
);
关于php - Regex Php 将方括号和大括号转换为 StackOverflow Reddit 等链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22776596/