i want to grab text from HTML do some process and change to it and reinsert to that HTML code with php.
<p>This is my sentence <span>and more</span> also <strong>important</strong> part.</p>
What’s the best method? Using preg_* ? how can i reinsert my text to HTML style ?
for example i want to remove all double or more spaces between words.
preg_replace('/\s+/', ' ', $myText);
but i want just applied in text of my html not html tags, attributes or etc …
Have a look at DomDocument. It’ll allow you to do some manipulation on your HTML.
http://www.php.net/manual/en/domdocument.loadhtml.php
EDIT
If you want to elaborate on exactly what you want to do with your HTML example, we might be able to provide a more specific answer 🙂
EDIT
To reflect the updated answer: the multiple spaces in HTML should collapse anyway, but if you want to remove them then you could try the following:
I’m not a regex expert by any stretch so I’m sure there’s a more elegant way to do this, but this might work for you nonetheless: first do a
preg_replace_callbackand use lookarounds to grab any text fragments between end and start tags. Then, pass the result throughpreg_filter(orpreg_replace) to replace any multiple spaces as a single space.Hope this helps/works 🙂