假设我需要更换以下任何一项:
{{image.jpg}}或者{{any-othEr_Fil3.JPG}}
至:
<img src="image.jpg" alt="" />或<img src="any-othEr_Fil3.JPG" alt="" />分别使用 PHP 和正则表达式。
计划是什么?
我一直在尝试,但没有成功。
要匹配的正则表达式(我假设文件名不包含}字符 - 如果它包含,那么必须有一个方案来转义它,我从您提供的信息中不知道):
/{{([^}]*)}}/
要替换的字符串:
'<img src="$1" alt="" />'
要匹配介于 the{{和 the之间的字符,}}我们应该使用(.+?). .匹配任何字符(包括空格)的方法。我允许这样做,因为file name.jpg它是一个有效的文件名(如果您不希望空格替换.+?为\S+?)。这+意味着需要有多个字符才能进行匹配。这?意味着正则表达式将尝试匹配尽可能少的字符。因此,如果我们使用正则表达式{{(.+?)}},捕获的字符将是最近的{{和集之间的字符}}。例如:
$string = '{{image.jpg}} or {{any-othEr_Fil3.JPG}}';
echo preg_replace_callback('/{{(.+?)}}/', function($matches) {
return sprintf('<img src="%s" alt="" />', $matches[1]);
}, $string);
会回声
<img src="image.jpg" alt="" /> or <img src="any-othEr_Fil3.JPG" alt="" />
正则表达式/{{\s*(.+?\.(?:jpg|png|gif|jpeg))\s*}}/i将匹配组之间的任何图像文件名(带有 jpg、png、gif 或 jpeg 文件扩展名),{{并}}在大括号和文件名之间留出空格。例如 :
$string = "{{image.jpg}} or {{ any-othEr_Fil3.JPG }} \n"
. "{{ with_spaces.jpeg }} and {{ this_is_not_an_image_so }} don't replace me \n"
. "{{ demonstrating spaces in file names.png }}";
$regexp = '/{{\s*(.+?\.(?:jpg|png|gif|jpeg))\s*}}/i';
echo preg_replace_callback($regexp, function($matches) {
return sprintf('<img src="%s" alt="" />', $matches[1]);
}, $string);
会回声
<img src="image.jpg" alt="" /> or <img src="any-othEr_Fil3.JPG" alt="" />
<img src="with_spaces.jpeg" alt="" /> and {{ this_is_not_an_image_so }} don't replace me
<img src="demonstrating spaces in file names.png" alt="" />
这是在 Perl 中,但在 PHP 中应该类似:
从命令行:
echo "{{image.jpg}} {{any-othEr_Fil3.JPG}}" | perl -ne '$_ =~ s/{{([^}]+)}}/<img src="$1" alt="" \/>/g; print $_'