J. Doe J. Doe - 3 years ago 162
PHP Question

How to find any variable word in a String with Regex in PHP

Example String:

Here are sample apartment pictures {img="/path/photo1.jpg" alt="I am Photo Title"} and {img="/path/photo2.jpg" alt="I am Photo Title #2"} this...

They must be found:

{img="/path/photo1.jpg" alt="I am Photo Title"}
{img="/path/photo2.jpg" alt="I am Photo Title 2"}

How can these image links be found in sentences?

Answer Source

$string = "Here are sample apartment pictures {img='/path/photo1.jpg' alt='I am Photo Title'} and {img='/path/photo2.jpg' alt='I am Photo Title #2'} this...";

preg_match_all("/({([\w]+)[^}]*})(.*?)/", $string, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
    echo "Variable Word In String: " . $val[1] . "<br>\n";

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download