PHP Shortcode正则表达式问题

PHP Shortcode正则表达式问题

问题描述:

Hi so I need help in taking a block of html which contains existing shortcode for an old arbitrary system. Taking the code below and and using PHP change so the following :

[CDC](http://www.cdc.gov/)

would be transformed into this :

<a href="http://cdc.gov">CDC</a> 

Any ideas on how i could achive this? There could be multiple instances in one block of code also. If anybody can help , I'd be grateful - thank you!!

嗨所以我需要帮助来获取包含旧任意系统的现有短代码的html块。 使用下面的代码并使用PHP更改以下内容: p>

[CDC](http://www.cdc.gov/) code> p>

将转换为: p>

 &lt; a href =“http://cdc.gov”&gt; CDC&lt; / a&gt;  
  code>  pre> 
 
 

关于如何实现这一点的任何想法? 一个代码块中也可能有多个实例。 如果有人可以提供帮助,我将不胜感激 - 谢谢!! p> div>

The solution using preg_replace function with specific regex pattern:

$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="$2">$1</a>', $block);

print_r($block);

The output(from source code):

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 ...

This should Work:

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>"
 ?>

Result:

<a href=http://www.cdc.gov/>CDC</a>

Enjoy.