i am doing some DOM parsing, and i have some strings i have to clean, they look like this:
$str1 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;getImgString()";
$str2 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;arrayImg[0]=
http://somepage.com/big/qingliang/2013-5-11/1/2.jpg
;getImgString()"
$str3 = "var arrayImg=new Array();arrayImg[0]=
http://somepage.com/2013-5-11/1/1.jpg
;arrayImg[0]=
http://somepage.com/2013-5-11/1/2.jpg
;arrayImg[0]=
http://somepage.com/2013-5-11/1/3.jpg
;getImgString()"
etc etc, you can see the system, i only need the last URL in the string, the amount of strings is variable, and the amount of links inside the strings is aswell, but i only need the last link in each string.
Should i use REGEX or a series of explode ?
With explode
$arr = explode(';',$str);
$arr = $arr[count($arr) - 2]; // get the last link
$arr = trim($arr,"arrayImg[0]="); //here you will get only the last link
Most of people stuck in situation whether they have to use regex or any other predefined functions. You have to use predefined functions if your task can be accomplished with them otherwise use regex if none of them available to accomplish your task.
If the string contain consistent pattern, use explode()
, it's panlessly easier and you don't have to worry about risk of regex-logic. Use regex
otherwise.
if you want exactly regex (not exploding the string) try this:
preg_match_all ("/http\S+/", $str, $matches);
$link = $matches[0][count($matches[0])-1];
UPD found an error, code updated