Split sentence(HTML code) into words by spaces and brackets

129 views Asked by At

For example I want to split following HTML code:

<a href="http://www.google.com">Google</a>

Output should be seperated by spaces as well as angle brackets

Array(
[0] => <
[1] => a
[2] => href="http://www.google.com"
[4] => >
[5] => Google
[6] => <
[7] => /a
[8] => >
2

There are 2 answers

2
Casimir et Hippolyte On BEST ANSWER

Not sure of what you are trying to achieve, but for your example, you can use the option PREG_SPLIT_DELIM_CAPTURE that includes captured parts of the delimiter in the result:

$result = preg_split('/([<>])| /', $txt, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
0
Kerwin On
>>> '<a href="http://www.google.com">Google</a>'
    .match(/(<)(\w+)\s+(href=\"[\w\/:.]+\")\s*(>)(.*)?(<)(\/\w)(>)/)

 ["<a href="http://www.google.com">Google</a>" 
  ,"<", "a", "href="http://www.google.com"", ">", "Google", "<", "/a", ">"]