Hello I'd like to know how can I do this: For example I have a string "I like <h1>digitalpoint</h1> forum because digitalpoint forum is good.". And I want to replace "digitalpoint forum" to "this forum". How can I do it by preg_replace function for replacing both "digitalpoint forum" ignoring html tags. Thank you
Hi, you don't need regular expression, here is my solution: $s="I like <h1>digitalpoint</h1> forum because digitalpoint forum is good."; echo str_ireplace('digitalpoint forum','this forum',strip_tags($s))."\r\n"; PHP: Regards Edit:OK, here is regex echo preg_replace('#\bdigitalpoint\s+forum\b#miu','this forum',strip_tags($s))."\r\n"; PHP:
Thanks for your reply koko5, but I need that the function returns "I like <h1>this</h1> forum because this forum is good." not "I like this forum because this forum is good.". And I want to do it by regular expression because I need replace the string like this: '/\bdigitalpoint forum\b(?![^<]*>)/i'
ok,maybe this: echo preg_replace('#(\bdigitalpoint)(\</[^\>]+\>)?(\s| )+(forum\b)#miu','this$2$3$4',$s)."\r\n"; PHP:
Thank you koko5, it works. But how can I do that it replaces the "digitalpoint" to "this" if "digitalpoint" is in several tags like this: <h1><u><i>digitalpoint</i></u></h1>. Thank you very very much again!!!
You are welcome, I'm glad to help if I can Replacing (\</[^\>]+\>)? to (\</[^\>]+\>)* will do the trick: echo preg_replace('#(\bdigitalpoint)(\</[^\>]+\>)*(\s| )+(forum\b)#miu','this$2$3$4',$s)."\n"; PHP: Regards
Sorry, finally I've fixed it (hope so) : echo preg_replace('#(\bdigitalpoint)((\</[^\>]+\>)*(\s| )+forum\b)#miu','this$2',$s)."\n"; PHP: