Here is my link
<img src='http://www.example.org/images/post_images/2400.jpg' /><div>© Ham Sammich</div></div>
I want to remove the text after the />
thus making the link..
<img src='http://www.example.org/images/post_images/2400.jpg' />
I've tried using the strstr()
function on the end, but my vps does not have the option of going to php5.3 thus making that not a go.
Here is my code, which does not work because of 5.3 not being on there..
$imgTwo = strstr($img, ">", 1);
$img = $imgTwo . ">";
Whats a good substitute for getting this done the way I want?
Oh the dark time before
strstr()
...Here is a selection of some possible methods:
Code: (Demo with PHP5.2.17)
Output:
strstr($string,'<div>',true);
-- this would have been the best call -- one function call creates the desired string, no extra function calls, no excess memory usage / no concatenation.strtok($string,'>'),'>'
-- this is nearly clean, but not quite because it can only seek a single character and so we must change the target and then concatenate the character at the end.substr($string,0,strpos($string,'<div>'))
-- it generates the desired substring from the string, but makes two function calls when just one call is desirable for this simple task.current(explode('<div>',$string))
-- this generates an array of unlimited elements, only to access the first string. It's two function calls and not very clean as it asks for more work to be done than is necessary.current(explode('<div>',$string,2));
-- limiting the elements is better than the previous explode method, but the same principle applies: why make an array when you only want a string.preg_match('/<img[^>]*>/',$string,$out)?current($out):'failed';
-- whether it is preg_match, preg_split, preg_replace, etc. regex patterns are notoriously slower than non-regex functions. For this case, there is no advantage to employing a regex approach. So while it is only one function call, it won't be the most efficient way.Do your own benchmarking if you like, but performance will be indistinguishable to your end user for such a small string.
The next criteria will be up to you. Perhaps you feel one way is easier to read than another, or perhaps you want a function that doesn't choke easily if the expected delimiter is missing.
$matches[0] will be just the
img
tag.There is alternative solution to the one given by @JonathanRich and it does not involve regular expressions.
where
$string
is your string and$result
is the result of processing.What it means? It says "split the string on "/>" and return part before its first occurence, then add "/>" to it and save as $result". Which means it does exactly what you wanted :)
Here is the demonstration that this actually works: codepad.org/0TTCypA5
There is also alternative solution to above alternative solution :)
the demonstration of which is here: codepad.org/ifyJiaPB. This one says: "find the position of first occurence of "/>" within the string and return everything before, including "/>" itself".