How to make html link with php regex

走远了吗. 提交于 2021-01-29 02:28:21

问题


My string

[[https://example.com|link]]

to convert

<a href="https://example.com>link</a>

My regex is

/\[{2}(.*?)\|(.*?)\]{2}/s

But it's not working.I am new to php regex.


回答1:


You may use

preg_replace('~\[\[((?:(?!\[\[).)*?)\|(.*?)]]~s', '<a href="$1">$2</a>', $string)

See the regex demo

Details

  • \[\[ - a [[ substring
  • ((?:(?!\[\[).)*?) - Group 1 ($1 in the replacement pattern refers to the value inside this group): any char (.), 0 or more occurrences but as few as possible (*?), that does not start a [[ char sequence ((?!\[\[))
  • \| - a | char
  • (.*?) - Group 2 ($2):
  • ]] - a ]] substring.

See the PHP demo:

$string = "[[some_non-matching_text]] [[https://example.com|link]] [[this is not matching either]] [[http://example2.com|link2]]";
echo preg_replace('~\[\[((?:(?!\[\[).)*?)\|(.*?)]]~s', '<a href="$1">$2</a>', $string);
// => [[some_non-matching_text]] <a href="https://example.com">link</a> [[this is not matching either]] <a href="http://example2.com">link2</a>


来源:https://stackoverflow.com/questions/61071810/how-to-make-html-link-with-php-regex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!