conker87 Posted July 22, 2009 Share Posted July 22, 2009 I'm looking to remove all punctuation and such from a string (not including spaces and apostrophes) THEN I'd like to replace the remaining spaces and apostrophes with dashes (-). I have absolutely no clue about regex, but I'm assuming the use of preg_replace() is needed. Can anyone enlighten me? Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted July 22, 2009 Share Posted July 22, 2009 Well, many ways to do that. Assuming that consecutive spaces or a mix of consecutive space then apostrophes are replaced with a single dash: $str = 'Here text has punctuation! But, I have a "question". Have you heard of Vézère River at Thonac? It\'s a beautiful place!'; $str = preg_replace('#[.?!,"]#', '', $str); $str = preg_replace('#[ \']+#', '-', $str); echo $str; You could also use a mix of regex / string translate: $str = 'Here text has punctuation! But, I have a "question". Have you heard of Vézère River at Thonac? It\'s a beautiful place!'; $str = strtr($str, array('.'=>'','?'=>'',','=>'','!'=>'','"'=>'')); // using string translate $str = preg_replace('#[ \']+#', '-', $str); echo $str; Quote Link to comment Share on other sites More sharing options...
conker87 Posted July 22, 2009 Author Share Posted July 22, 2009 That's brilliant. Are either ways more efficient that one another? Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted July 22, 2009 Share Posted July 22, 2009 I would think the one using strtr would probably be faster, as string functionality outstrips regex in raw speed (but in truth, the amount of text would have to be quite huge to start seeing the speed differences between the two methods.. so for modest text, it probably doesn't really matter much I'd guess). Quote Link to comment Share on other sites More sharing options...
conker87 Posted July 22, 2009 Author Share Posted July 22, 2009 They're just stripping out titles, which are never more than 100 characters long anyway. Thanks for the help, saved me a load of time. Quote Link to comment Share on other sites More sharing options...
nrg_alpha Posted July 22, 2009 Share Posted July 22, 2009 Yeah, for strings that short, either solution (along with go knows how many more are out there) will do. Please flag this thread as 'Solved'. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.