PHP - preg_replace 多个模式,同时保留其他两个模式之间的内容
PHP - preg_replace multiple patterns, while keeping what's inbetween two other patterns
我最近开始使用正则表达式函数来简化我以前的工作。我正在尝试打开它,
Some text
'[img="http://www.example.com/null.jpg"]'
Some more text
进入这个:
Some text
<img src="http://www.example.com/null.jpg">
Some more text
这在 php 中是否可以使用正则表达式函数(例如 'preg_replace' 和 'preg_match')?
***编辑[
这是我目前笨拙的函数
function filterimgorig($string)
{
if(substr_count($string, '[img="')==substr_count($string, '"]') and substr_count($string, '[img="')+substr_count($string, '"]')!=0)
{
$start = strpos($string, '[img="')."<br/>";
$end = strpos($string, '"]');
$img = substr($string, $start+6, ($end - $start)-6);
if (filter_var($img, FILTER_VALIDATE_URL) === false) {
return htmlspecialchars(str_replace(''',"'",$string));
}
else
{
return substr($string, 0, $start)."\r\n<img src='".$img."'>\r\n".substr($string, $end+2,strlen($string));
}
}
else
{
return htmlspecialchars(str_replace(''',"'",$string));
}
}
你可以这样做:
$string = preg_replace("/'\[img=([^]]+)\]/", "<img src=>", $string);
我最近开始使用正则表达式函数来简化我以前的工作。我正在尝试打开它,
Some text
'[img="http://www.example.com/null.jpg"]'
Some more text
进入这个:
Some text
<img src="http://www.example.com/null.jpg">
Some more text
这在 php 中是否可以使用正则表达式函数(例如 'preg_replace' 和 'preg_match')?
***编辑[
这是我目前笨拙的函数
function filterimgorig($string)
{
if(substr_count($string, '[img="')==substr_count($string, '"]') and substr_count($string, '[img="')+substr_count($string, '"]')!=0)
{
$start = strpos($string, '[img="')."<br/>";
$end = strpos($string, '"]');
$img = substr($string, $start+6, ($end - $start)-6);
if (filter_var($img, FILTER_VALIDATE_URL) === false) {
return htmlspecialchars(str_replace(''',"'",$string));
}
else
{
return substr($string, 0, $start)."\r\n<img src='".$img."'>\r\n".substr($string, $end+2,strlen($string));
}
}
else
{
return htmlspecialchars(str_replace(''',"'",$string));
}
}
你可以这样做:
$string = preg_replace("/'\[img=([^]]+)\]/", "<img src=>", $string);