Replace one character with another

5 posts by 2 authors in: Forums > CMS Builder
Last Post: August 30, 2009   (RSS)

Re: [gkornbluth] Replace one character with another

By Chris - August 29, 2009

Hi Jerry,

Here's the code you're looking for:

$record['group_code'] = preg_replace("/[-_]/", " ", $record['group_code'] );

/[-_]/ means "match a single character in the set [-_]". preg_replace() will repeat the match as many times as it can.

/^\s*-/i means "match from the start of the string, allowing any number of whitespace chatacters (i.e. tabs, spaces, newlines), then a single - character, without respect to case".

Regular expressions can be very tricky.

Hope this helps! Please let us know if you have any more questions or comments! :)
All the best,
Chris

Re: [chris] Replace one character with another

By gkornbluth - August 29, 2009 - edited: August 29, 2009

It worked perfectly (what did I expect). And tricky is definitely the word of the day.

Thanks!!!

And thanks for the explanation as well.

So if I wanted to replaced any dashes or underscores with spaces as well, would I add the entire snippet again, including the comma?

"/[__]/", "/[-_]/",

Also, how would I replace a dash with a space, and an underscore with a star (just to demonstrate the replacement of 2 (or more) characters with other specific characters?

Thanks again, and again, and....

Jerry
The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php

Re: [gkornbluth] Replace one character with another

By Chris - August 29, 2009

Hi gkornbluth,

The first argument (before the comma) is the pattern to match; the second argument is what the match should be replaced with.

$record['group_code'] = preg_replace("/-/", " ", $record['group_code'] );

The above code will replace any occurrence of a dash ("-") in the string with " ".

$record['group_code'] = preg_replace("/[-_]/", " ", $record['group_code'] );

The above code will replace any occurrence of either a dash ("-") or an underscore ("_") in the string with " ".

$record['group_code'] = preg_replace("/-/", " ", $record['group_code'] );
$record['group_code'] = preg_replace("/_/", "*", $record['group_code'] );


The above code will replace any occurrence of a dash ("-") in the string with a space (" "). Then it will replace any occurrence of an underscore ("_") with an asterisk ("*").

Hope this helps! You might want to read a chapter or two on regular expressions if you want to learn how this stuff all works. :)
All the best,
Chris

Re: [chris] Replace one character with another

Chris,

Thanks for the explanation.

It helps to understand and not just paste some code.

Best,

Jerry
The first CMS Builder reference book is now available on-line!







Take advantage of a free 3 month trial subscription, only for CMSB users, at: http://www.thecmsbcookbook.com/trial.php