PHP 简码正则表达式问题
PHP Shortcode Regex issue
嗨,所以我需要帮助来获取 html 的一个块,其中包含一个旧的任意系统的现有短代码。使用下面的代码并使用 PHP 更改如下:
[CDC](http://www.cdc.gov/)
会变成这样:
<a href="http://cdc.gov">CDC</a>
关于如何实现此目标的任何想法?一个代码块中也可能有多个实例。如果有人可以提供帮助,我将不胜感激 - 谢谢!!
使用具有特定正则表达式模式的 preg_replace
函数的解决方案:
$block = "Two excellent websites outlining the major precautions are: [some text](www.cdc.gov) and [who's next](www.who.int) which are the official sites ...";
$block = preg_replace("/\[([^]]+)\]\(([^)]+)\)/", '<a href=""></a>', $block);
print_r($block);
输出(来自源代码):
Two excellent websites outlining the major precautions are: <a href="www.cdc.gov">some text</a> and <a href="www.who.int">who's next</a> which are the official sites ...
这应该可行:
PHP:
<?php
$re = '/(?<=\[)[^]]+(?=\])|(?<=\()[^]]+(?=\))/m';
$str = '[CDC](http://www.cdc.gov/)';
preg_match_all($re, $str, $matches);
// Print the entire match result
//print_r($matches); //Print result
$url = $matches[0][1]; //http://www.cdc.gov/
$text_url = $matches[0][0]; //CDC
echo "<a href=".$url.">$text_url</a>"
?>
结果:
<a href=http://www.cdc.gov/>CDC</a>
尽情享受吧。
嗨,所以我需要帮助来获取 html 的一个块,其中包含一个旧的任意系统的现有短代码。使用下面的代码并使用 PHP 更改如下:
[CDC](http://www.cdc.gov/)
会变成这样:
<a href="http://cdc.gov">CDC</a>
关于如何实现此目标的任何想法?一个代码块中也可能有多个实例。如果有人可以提供帮助,我将不胜感激 - 谢谢!!
使用具有特定正则表达式模式的 preg_replace
函数的解决方案:
$block = "Two excellent websites outlining the major precautions are: [some text](www.cdc.gov) and [who's next](www.who.int) which are the official sites ...";
$block = preg_replace("/\[([^]]+)\]\(([^)]+)\)/", '<a href=""></a>', $block);
print_r($block);
输出(来自源代码):
Two excellent websites outlining the major precautions are: <a href="www.cdc.gov">some text</a> and <a href="www.who.int">who's next</a> which are the official sites ...
这应该可行:
PHP:
<?php
$re = '/(?<=\[)[^]]+(?=\])|(?<=\()[^]]+(?=\))/m';
$str = '[CDC](http://www.cdc.gov/)';
preg_match_all($re, $str, $matches);
// Print the entire match result
//print_r($matches); //Print result
$url = $matches[0][1]; //http://www.cdc.gov/
$text_url = $matches[0][0]; //CDC
echo "<a href=".$url.">$text_url</a>"
?>
结果:
<a href=http://www.cdc.gov/>CDC</a>
尽情享受吧。