Reputation: 7703
Say I need to replace any of the following:
{{image.jpg}}
or {{any-othEr_Fil3.JPG}}
To:
<img src="image.jpg" alt="" />
or <img src="any-othEr_Fil3.JPG" alt="" />
respectively using PHP and regex.
What would be the scheme?
I've been trying, but unsuccessfully.
Upvotes: 0
Views: 649
Reputation: 7245
To match the characters in between the {{
and the }}
we should use (.+?)
. The .
means to match any character including white space. I allowed for this since file name.jpg
is a valid file name (if you don't want white space replace .+?
with \S+?
). The +
means that there needs to be more than one character for the match to happen. The ?
means that the regexp will try to match as few characters as possible. So then if we use the regexp {{(.+?)}}
the captured characters will be those in between the nearest sets of {{
and }}
. For example:
$string = '{{image.jpg}} or {{any-othEr_Fil3.JPG}}';
echo preg_replace_callback('/{{(.+?)}}/', function($matches) {
return sprintf('<img src="%s" alt="" />', $matches[1]);
}, $string);
Will echo
<img src="image.jpg" alt="" /> or <img src="any-othEr_Fil3.JPG" alt="" />
The regexp /{{\s*(.+?\.(?:jpg|png|gif|jpeg))\s*}}/i
will match any image file names (with jpg, png, gif, or jpeg file extensions) in between sets of {{
and }}
allowing for space in between the curly brackets and the file name. For example :
$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);
Will echo
<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="" />
PHP preg_replace_callback documentation
The site I use to test and practice regular expressions
Upvotes: 1
Reputation: 203
This is in Perl but should be similar in PHP:
From command line:
echo "{{image.jpg}} {{any-othEr_Fil3.JPG}}" | perl -ne '$_ =~ s/{{([^}]+)}}/<img src="$1" alt="" \/>/g; print $_'
Upvotes: 0
Reputation: 56829
The regex to match (I assume that file name does not contain }
character - if it does contains, then there must be a scheme to escape it, which I don't know from your provided information):
/{{([^}]*)}}/
The string to replace:
'<img src="$1" alt="" />'
Upvotes: 2