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?

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.