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
https://forums.phpfreaks.com/topic/215995-regular-expression-help/
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);

 

 

 

 

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

 

 

 

 

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.