php - Regex Php 将方括号和大括号转换为 StackOverflow Reddit 等链接

标签 php regex hyperlink

我正在尝试将用户在存储在 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/

相关文章:

php - 错误! : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

javascript - 如何在正则表达式构造函数中包含符号?

html - 我怎样才能一次导入所有谷歌字体?

python - 如何使用 QWebEngine 在同一窗口中打开任何链接(_blank)

Javascript 通过 id 链接到 div

javascript - 表单输入显示图像而不是文本值

php - MySQL问题从一个表直接复制到另一个表

regex - 正则表达式匹配字符串-正向提前

php - 找不到类 App\Articles

php - 从字符串中获取电子邮件 - 正则表达式语法 + preg_match_all