-1

I need delimiter a string (it's html) and i need extract a substring, but i only have a function to delimiter by the left:

function ddd($str, $sLeft, $sRight)
{
$pleft = strpos($str, $sLeft, 0);
$pright = strpos($str, $sRight, $pleft + strlen($sLeft));
return (substr($str, $pleft + strlen($sLeft), ($pright - ($pleft + strlen($sLeft)))));
}

but i need start on the right ($sRight) and end at $sLeft. Thanks!

fj123x
  • 6,904
  • 12
  • 46
  • 58

1 Answers1

1

If I understand you correctly, you need to search the string by the left side, and also by the right side. If that is the case you can use this function:

PHP

<?php

// Function from php.net, see the link above.
// Starts searching the value from the right side
// of the string, returning the pos
function backwardStrpos($haystack, $needle, $offset = 0){
    $length = strlen($haystack);
    $offset = ($offset > 0)?($length - $offset):abs($offset);
    $pos = strpos(strrev($haystack), strrev($needle), $offset);
    return ($pos === false) ? (false) : ($length - $pos - strlen($needle));
}

$string = 'My string is this, and it is a good dialog';
echo backwardStrpos($string, "i"); // outputs 37
echo strpos($string, "i", 0);      // outputs 6

?>

ILLUSTRATED VERSION OF THE OUTPUT:

enter image description here


EDITED

You've just placed a comment related to what you are trying to do.

For that you can use PHP strip_tags:

<?php

$str = '<div><span class="some style bla bla assd dfsdf">ImportantText</span>';

echo strip_tags($str); //outputs: ImportantText

?>

EDITED

To extract text between HTML tags:

<?php

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<div><span class="some style bla bla assd dfsdf">ImportantText</span>';
$txt = getTextBetweenTags($str, "span");
echo $txt; // outputs: ImportantText

?>

This came from a fellow stackoverflow! link

Community
  • 1
  • 1
Zuul
  • 16,217
  • 6
  • 61
  • 88
  • I have more text but only one in and i only need this – fj123x May 15 '12 at 12:56
  • See my last edit at the end of my answer! With that small function you can collect the text between your span, or any other HTML tag. – Zuul May 15 '12 at 13:04