Link to home
Start Free TrialLog in
Avatar of rohgan
rohgan

asked on

Extract a word from a string

I have a variable that contains img tag. example:

 <img src="folder1/folder2/filename.jpg" width="123" height="123">
OR
 <img src="filename123.jpg" width="123" height="123">


I need php code to extract folder1/folder2/filename.jpg or filename123.jpg based on the input string.
ASKER CERTIFIED SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wack_izzy
wack_izzy

So if understand correctly, you have a variable which has, <img src="filename123.jpg" width="123" height="123"> as the value (or something to that effect)?

The only way I know how to do what your asking is with Regular Expressions. View the code below.

<?php
$pattern = '/<.*?src *?=[\'"](.*?)[\'"].*?>/i';

$text = "<img src=\"filename123.jpg\" width=\"123\" height=\"123\">";
preg_match($pattern, $text, $matches);

print_r($matches);
?>

Basically it runs a regular expression pattern that pulls out information within the src="" area, and places it into an array. When you print the array you'll see the value you want is in $matches[2], which it will always be when running the specific pattern.