RafaelM
RafaelM

Reputation: 159

Replace multiple strings with one string

I'm trying to replace several possible strings with only one in PHP. Also, the strings must match only a complete word:

<?

$rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here.";

//strings for substitution
$placeholders = array('N/A', 'NA', 'NONE');

//replace with blank spaces. 
$substitution = array('');

$greeting = str_ireplace($placeholders, $substitution, $rawstring);

echo  $greeting . "<br />";
?>

This is the resulting string:

Hello . Your is a pleasure to have! Your friend Johan is also here.

This is almost the output I'm looking for. I would like the substitution to only affect individual words. In this case, it's replacing the 'na' in 'Johanna', resulting in 'Johan'. It should still print out 'Johanna' .

Is this possible?

EDIT: I cannot control $rawstring. This is just an example.

Upvotes: 0

Views: 331

Answers (3)

cpilko
cpilko

Reputation: 11852

To not match parts of a word, you're going to need to use preg_replace().

Try something like this:

$rawstring = "Hello NONE. Your N/A is a pleasure to have! Your friend Johanna is also here.";
$placeholders = array('N/A', 'NA', 'NONE');

//Turn $placeholders into an array of regular expressions
//  `#` delimits the regular expression. Make sure this doesn't appear in $placeholders.
//  `(.+)` matches and captures any string of characters
//  `\b` matches word boundaries
//  `${1}` reinserts the captured pattern.
//  `i` at the end makes this case insensitive.
$re = preg_replace('#(.+)#', '#\b${1}\b#i', $placeholders); 

//Make the same substitution for all matches.
$substitution = '';

$greeting = preg_replace($re, $substitution, $rawstring);
echo  $greeting;

Upvotes: 2

Adam T
Adam T

Reputation: 675

I'd set up an associative array to set up the vars for replace. - edit, had to escape the slash in N/A

$val_to_swap_in = '';
$replacers = array(
    '/NONE/' => $val_to_swap_in,
    '/N\/A/' => $val_to_swap_in, 
    '/NA/'   => $val_to_swap_in,
);
$greeting = preg_replace(array_keys($replacers), array_values($replacers),  $rawstring);

Resulted in this in php cli shell:

Hello . Your  is a pleasure to have! Your friend Johanna is also here.

Upvotes: 0

Squeegy
Squeegy

Reputation: 869

I'd look at http://php.net/sprintf if you already know the string and are just looking to sub in certain spots. Sorry for the answer I don't have enough rep yet to comment.

Upvotes: 0

Related Questions