Jump to content

[SOLVED] Removing all but Spaces and Apostrophes


conker87

Recommended Posts

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?

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;

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).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.