user949738
user949738

Reputation: 115

str_replace and numbers

The issue I'm having is I need to replace a few variables in strings with data, for example:

Blah blah S_10 blah S_1 blah blah S_5 blah blah S_15

So the problem is when I iterate through all of the strings, the S_1 replacement undesirably can replace the first 3 characters of S_10 and S_15, so the string will look like

Blah blah APPLE0 blah APPLE blah blah ORANGE blah blah APPLE5

What's the best way to approach this challenge?

Upvotes: 2

Views: 367

Answers (5)

lpostula
lpostula

Reputation: 584

You can go through the string looking for 'S_' when you find it, you identify the number, and replace it with the corresponding item, so:

<?php
 $text = "Blah blah S_10 blah S_1 blah blah S_5 blah blah S_15";
 for($i=0;$i<strlen($text);$i++){
 if($text[$i] == "S" and $text[$i+1] == "_"){
     $j = $i+2;
     while($text[$j] != " "){$j++;}
     $value = substr($text, $i,$j-1);
     $text = substr($text, 0, $i-1)+replace($value)+substr($text, $j);
     }
  }
?>

and in the function replace, you replace the S_* by what you want

Upvotes: 0

ZiTAL
ZiTAL

Reputation: 3581

with preg replace:

?php
$a = "Blah blah S_10 blah S_1 blah blah S_5 blah blah S_15";
$search = array("/S_1([0-9]+|)/", "/S_5([0-9]+|)/");
$replace = array('APPLE', 'ORANGE');

$a = preg_replace($search, $replace, $a);

echo $a;
?>

Upvotes: -1

Gumbo
Gumbo

Reputation: 655219

Instead of replacing one term at a time, find all terms and replace them at once. You can use preg_replace_callback to perform a regular expression search and call a function for each match to replace it with the corresponding replacement:

$mapping = array('S_1' => 'APPLE', 'S_2' => 'ORANGE');
$output = preg_replace_callback('/S_\d+/', function ($match) use ($mapping) {
    return array_key_exists($match[0], $mapping) ? $mapping[$match[0]] : $match[0];
}, $input);

Upvotes: 3

Rezigned
Rezigned

Reputation: 4922

Here's the tip that you can always use arrange the search keys by length/value in descending order

str_replace(array('S_15', 'S_10', 'S_1'), array('your replacements'), $string);

Upvotes: 2

Gohn67
Gohn67

Reputation: 10638

Probably not the best solution, but given the information presented. Maybe you can you use the string replace method (str_replace) using an order of S_15, S_10, S_5, followed by S_1. That way you don't get that conflict.

Upvotes: 0

Related Questions