Question

Is it possible to find all tags in string with their positions?

For example for following text:

#$text = file_get_contents($file); # for the simplicity - see other line:
$text = "<tag> sometext <tag2> more text </tag2>";

in the result i would like to get all tags from $text and their positions:

 - [0] name = <tag>, position = 1

 - [1] name = <tag2>, position = X

 - [2] name = </tag2>, position = X

As I understand - a regex shall be used. If it helps - I know the names of all tags. For the simplicity here they are:

<tag>, <tag1>, <tag2>, <tag3>, </tag>, </tag1>, </tag2>, </tag3>

What's the best approach to get the desired result?

Was it helpful?

Solution

You can use following regex:

preg_match_all('@(\</?[a-z0-9]+\>)@', $text, $m);

$tags = array();
foreach ($m[1] as $i => $match) {
  echo "name = " . $m[1][$i] . ", position = " . ($i+1) . "\n";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top