Replace one character with another

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

Well, I'm stumped again.

I'm trying to replace any occurrence of a dash (-) in the contents of a field with a space and then print the field contents (with the spaces) and I've not been able to get it to work.

I'd ultimately like to replace any occurrence of a dash or an underscore with spaces.

Here's what I've tried to use so far based on some things that I found in the forum.

<?php foreach ($portfolio_imagesRecords as $record): ?>

<?PHP $record['group_code'] = preg_replace("/^\s*-/i", "&nbsp;", $record['group_code'] ); ?>

<?php echo $record['group_code'] ?>

<?php break ?>

<?php endforeach; ?>


Anyone who can point me in the right direction?

Thanks,

Jerry Kornbluth
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 Jerry,

Here's the code you're looking for:

$record['group_code'] = preg_replace("/[-_]/", "&nbsp;", $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: [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