具体link句中
Specific link in sentence
$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/' alt=''/>", $input_lines);
正则表达式代码:
/({\w+)/
图片链接:
{img='3512.jpg', alt='Title'}
and {img='3513.jpg', alt='Title2'}
in sentence.
转换:
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 组 {
和左大括号后的一个或多个单词字符。在您的替换模式中,有 </code> 和 <code>
替换反向引用不能 "work" 因为您只有一个捕获组。
您可以使用
$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 个或多个字母、数字 or/and _
='
- ='
文字子串
([^']*)
- 第 1 组:除 '
之外的任何 0+ 个字符
'
- 一个'
\s*,\s*
- 用 0+ 个空格括起来的逗号
\w+=
- 1 个或多个字母、数字 or/and _
和一个 ='
'
- 一个 '
([^']*)
- 第 2 组:除 '
之外的任何 0+ 个字符
'}
- '}
字符串。
$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/' alt=''/>", $input_lines);
正则表达式代码:
/({\w+)/
图片链接:
{img='3512.jpg', alt='Title'}
and {img='3513.jpg', alt='Title2'}
in sentence.
转换:
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 组 {
和左大括号后的一个或多个单词字符。在您的替换模式中,有 </code> 和 <code>
替换反向引用不能 "work" 因为您只有一个捕获组。
您可以使用
$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 个或多个字母、数字 or/and_
='
-='
文字子串([^']*)
- 第 1 组:除'
之外的任何 0+ 个字符
'
- 一个'
\s*,\s*
- 用 0+ 个空格括起来的逗号\w+=
- 1 个或多个字母、数字 or/and_
和一个='
'
- 一个'
([^']*)
- 第 2 组:除'
之外的任何 0+ 个字符
'}
-'}
字符串。