-3

Here is the deal. I have a string which contains a html <a><img /></a> tag at the very beginning. The string is returning form an rss. What i need is split the string into two. One i want to have the <a><img></a> and rest of the string in other variable.

Algorithm:

  • Check if the string starts with <a><img></a>
  • find the <a><img></a> and save in a variable.
  • remove <a><img></a> from original string.
  • return both variable.

Example

    <a href=""><img src="" /></a> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse eros. Nam augue. Morbi fermentum elit sit amet metus. Cras libero nulla, 
ultricies pulvinar, dapibus eu, tempus et, turpis. Donec urna ligula, commodo ac, tristique ut, egestas eu, justo. Fusce consectetuer vehicula magna. In turpis risus, malesuada et, commodo eget, ornare et, mauris.

Problem:

Can't figure out how to do it in php. I have seen some code in this site which includes regex and parsing all over the string. I want to find out a way where in the regex function breaks when it have the first match and not go through all over the string. Will use it inside a loop so concerning about the speed.

Sisir
  • 2,668
  • 6
  • 47
  • 82

1 Answers1

4

If you can guarantee that your input string will ALWAYS be in this format, then:

$closetag = strpos($input, '</a>') + 4; // strpos will return position of `<`, so move up 4 chars

if ($closetag !== FALSE) {
    $first = substr($input, 0, $closetag);
    $last = substr($input, $closetag);
} else {
    $first = $last = 'ERROR';
}
Marc B
  • 356,200
  • 43
  • 426
  • 500