Jump to content

Regular Expression Help


myares

Recommended Posts

I wanted to sort out a code which will work like this (for any variable):

 

$x = "A.S.M. Jackel"

$x = "A. S. M. Jackel"

 

I mean it will check the variable and if the variable doesn't have a space next to the . [dot] it will replace it and add a space next to it. If it already have a space next to the . [dot] it won't change anything. Can someone help me out?

Link to comment
Share on other sites

preg_replace is what you want to look at.  Check this out:

 

 



$x = "A.S.M. Jackel";
$y = "A. S. M. Jackel";

$pattern = '/(\.)([^ ])/';
$replace = '$1 $2';

echo preg_replace($pattern, $replace, $x);
echo '   ';
echo preg_replace($pattern, $replace, $y);

 

 

 

 

Link to comment
Share on other sites

For what it's worth, life could be made simpler by using a regular expression which reads like match a dot which is not followed by a space character:

 

$pattern = '/\.(?! )/';
$replace = '. ';

 

The (?! ) is a "negative lookahead assertion" and is a fancy way of saying, "take a peek at the next character and make sure it is not a space". See http://php.net/regexp.reference.assertions

 

 

 

 

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.