Php str_replace not working

6k views Asked by At

i've got a long string which is space delimited (read in from a txt file)

Input String:

$value = "TestNumber1  X Chan 1 Wrap Hi (5.0 V) (UNC)    9.860           V        GELE (>= <=) 9.750           10.250          Passed"

What I want to do, and have done succesfully is explode this string into a array using:

$Exploded = explode("  ",$value);

Unfortunatly though, I also want to seperate between the GELE (>= <=) part, and the following number (in this case 9.750), so I thought to make this easy, before I explode the string I'll do:

$value = str_replace("GELE (>= <=) ","GELE (>= <=)  ",$value);

The problem is, for some reason the replace isn't working. It's as if it's not seeing the needle. This is what my exploded string array is giving me after doing the str_replace.

Array ( [0] => TestNumber1 X Chan 1 Wrap Hi (5.0 V) (UNC) [1] => 9.860 [2] => V [3] => GELE (>= <=) 9.750 [4] => 10.250 [5] => Passed [6] => ) 

As you can see, element [3] => GELE (>= <=) 9.750

Is there anything stupid I'm doing here to make my str_replace function not work?

Thanks in advance.

3

There are 3 answers

0
Adam Hopkinson On BEST ANSWER

The whitespace after the string may be a tab character rather than spaces.

Try first replacing tabs \t with spaces.

0
xzyfer On

try:

preg_replace('/GELE\s*?\(>= <=\)(\s+)[0-9\.]*/', '  ', $value);
0
Akarun On

You can also explode your string using a regular expression, depending on what you really want for data.

If you want extract numbers like "9.860", "9.750" and "10.250" like this:

$iReg = preg_match("/^.*UNC\)[\s|\t]*([0-9\.]*).*<=\)[\s|\t]*([0-9\.]*)[\s|\t]*([0-9\.]*)[\s|\t]*(.*)/i", $sData, $aData);

echo "<p>iReg :".$iReg."</p>";
echo "<p><pre>".print_r($aData, true)."</pre></p>";

This code return this result:

Array
(
    [0] => TestNumber1  X Chan 1 Wrap Hi (5.0 V) (UNC)    9.860           V        GELE (>= <=) 9.750           10.250          Passed
    [1] => 9.860
    [2] => 9.750
    [3] => 10.250
    [4] => Passed
)

Hope this help you...

Aka