Frantisek
Frantisek

Reputation: 7703

How to use regex to replace image names to img tags?

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

Answers (3)

Will
Will

Reputation: 7245

Quick fix

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="" />

Getting fancy

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="" />

More Resources

PHP preg_replace_callback documentation

The site I use to test and practice regular expressions

Upvotes: 1

user1884047
user1884047

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/{{([^}]+)}}/&lt;img src="$1" alt="" \/&gt;/g; print $_'

Upvotes: 0

nhahtdh
nhahtdh

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

Related Questions