I want to insert a string on the 3rd word of a sentence. Usually we can explode() by spaces, but this string may contain HTML tags, and the HTML tags must be ignored when counting word.. For example want to insert "XXXXX" between 2nd and 3rd words. i have these string : Input = hello world i am xrvel Expected output = hello world XXXXX i am xrvel Input = hello world <img src="haha.jpg" /> i am xrvel Expected output = hello world <img src="haha.jpg" /> XXXXX i am xrvel OR hello world XXXXX <img src="haha.jpg" /> i am xrvel Input = hello world <img src="haha.jpg" /> i <strong title="me">am</strong> xrvel Expected output = hello world <img src="haha.jpg" /> XXXXX i <strong title="me">am</strong> xrvel OR hello world XXXXX <img src="haha.jpg" /> i <strong title="me">am</strong> xrvel
Use php str_word_count() followed by str_replace ie: find the second word and replace with second word plus XXXXX
You would need to strip the html out first, then count the words then insert the xxxxxx after the second word, then insert the html back in where it was.
I dont think it will work, there is HTML tag problem if we just use normal str_replace. Okay, but how to insert the html back? Which means we should remember the position of each html. I have no idea..
Not fully tested, but it should give you some idea... <?php $str = "hello world <img src=\"haha.jpg\" /> i am xrvel"; $strip = strip_tags($str); $get_word = str_word_count($strip,1); $new_str = str_replace(" $get_word[1] ", " $get_word[1] xxxxx ", $str); // change 1 to 0,2,3 or 4 for positioning of xxxxx echo $new_str; ?> PHP: Out-put: hello world xxxxx i am xrvel html out-put: hello world xxxxx <img src="haha.jpg" /> i am xrvel Code (markup): Take note of the spaces on the str_replace or else it will change all letters or words matching