PHP Shortcode正则表达式问题

时间:2017-01-09 18:38:41

标签: php regex shortcode

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

Calls<com.company.model.beans.Model> calls = new Calls<>(){};

将转变为:

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

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

2 个答案:

答案 0 :(得分:3)

使用具有特定正则表达式模式的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="$2">$1</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 ...

答案 1 :(得分:0)

这应该有效:

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>

<强>享受。