句子中的具体环节

时间:2017-10-01 08:22:00

标签: php regex preg-replace

$input_lines = 'this photos {img='3512.jpg', alt='Title'} and {#img='3513.jpg', alt='Title2'} any image code here related to image must be replaced.';
echo preg_replace("/({\w+)/", "<img src='https://imgs.domain.com/images/$1' alt='$2'/>", $input_lines);

正则表达式代码:

/({\w+)/

图片链接:

句子中的

{img='3512.jpg', alt='Title'}{img='3513.jpg', alt='Title2'}

转化:

this photos <img src='https://imgs.domain.com/images/3512.jpg' alt='Title'/><img src='https://imgs.domain.com/images/3513.jpg' alt='Title2'/> any image code here related to image must be replaced.

我在句子中得到图片链接,但正则表达式代码有什么问题?

1 个答案:

答案 0 :(得分:0)

您的({\w+)模式仅匹配并捕获到组1中的{和一个或多个单词字符在开括号之后。在您的替换模式中,有$1$2替换反向引用,因为您只有一个捕获组,因此无法“正常工作”。

您可以使用

$re = "/{#\w+='([^']*)'\s*,\s*\w+='([^']*)'}/";
$str = "this photos {#img='3512.jpg', alt='Title'} and {#img='3513.jpg', alt='Title2'} any image code here related to image must be replaced.";
$subst = "<img src='https://imgs.domain.com/images/\$1' alt='\$2'/>";
echo preg_replace($re, $subst, $str);

请参阅PHP demo,输出

this photos <img src='https://imgs.domain.com/images/3512.jpg' alt='Title'/> and <img src='https://imgs.domain.com/images/3513.jpg' alt='Title2'/> any image code here related to image must be replaced.

请参阅regex demo

<强>详情

  • {# - 子字符串{#
  • \w+ - 一个或多个字母,数字或/和_
  • =' - ='文字子字符串
  • ([^']*) - 第1组:除'
  • 以外的任何0 +字符
  • ' - '
  • \s*,\s* - 用0 +空格包围的逗号
  • \w+= - 一个或多个字母,数字或/和_以及='
  • ' - '
  • ([^']*) - 第2组:除'
  • 以外的任何0 +字符
  • '} - '}字符串。