$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.
我在句子中获取映像链接,但是正则反正代码怎么了?
您的 ({w+)
模式仅匹配并捕获到第1组A {
和一个或多个单词char之后。在您的替换模式中,有$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演示,输出
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.
请参阅正则演示。
详细信息
-
{#
-a子弦{#
-
w+
-1或更多字母,数字或/和_
-
='
- a='
字面底带 -
([^']*)
-组1:'
以外的任何0 字符 -
'
-'
-
s*,s*
-一个带有0 Whitespaces的逗号 -
w+=
-1或更多字母,数字或/和_
和='
-
'
-a'
-
([^']*)
-组2:'
以外的任何0 字符 -
'}
-a'}
字符串。