1

How to use php to find the first letter position which is not part of html tag. For example the following html string. I want to find the letter 'S' position which is the first letter of Stackoverflow.

<p><a href="http://url" target="_blank" >Stackoverflow</a> <a href="http://url" >is</a> usefull for developers.</p>
Tester
  • 798
  • 2
  • 12
  • 32

2 Answers2

0

You do this with an HTML parser, look at DOMDocument::loadHTML or DOMDocument::loadHTMLFile. You can then traverse the DOM tree to locate a text element. This in turn can be done by traversing the children elements recursively or use XPath to locate the desired DOM node.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

If it's for HTML rendering then you can use the CSS ::first-letter Selector

If it's for general string work then I've not found a versatile method yet, but a traditional code implementation (that may be slower) works:

function pos_first_letter($haystack) {
  $ret = false;
  if (!empty($haystack)) {
    $l = strlen($haystack);
    $t = false;
    for ($i=0; $i < $l; $i++) {
      if (!$t && ($haystack[$i] == '<') ) $t = true;
      elseif ($t && ($haystack[$i] == '>')) $t = false;
      elseif (!$t && !ctype_space($haystack[$i])) {
        $ret = $i;
        break;
      }
    }
  }
  return $ret;
}

Then call:

$i = pos_first_letter( $your_string );
if ($i !== false) {
  $output = substr($s, 0, $i);
  $output .= '<span>' . substr($s, $i, 1) . '</span>';
  $output .= substr($s, $i+1);
}