1

I'm using this code to get first number and replace it with 0-9, but I always get 0-0-9 result. Then I deleted in array 9 it started to work correct. why it works that way ?

$direction = strtoupper(substr($query_row["Band"],0,1));

$replace = [
'0' => '0-9','1' => '0-9','2' => '0-9','3' => '0-9','4' => '0-9',
'5' => '0-9','6' => '0-9','7' => '0-9','8' => '0-9', '9' => '0-9' ];

$dir= str_replace(array_keys($replace), $replace, $direction); 
5
  • Remove , start in array Commented Oct 30, 2015 at 10:13
  • Typo $replace = [ ,'0' Commented Oct 30, 2015 at 10:14
  • i understood your problem why it is happening as you replace 0 => 0-9 and then 9 => 0-9 which means 0 becomec 0-0-9 Searching for a solution please wait Commented Oct 30, 2015 at 10:20
  • I think you have a problem with multiple numbers in $direction. If you have more than 1 number it will replace all of these, not only the first one. Please give an example for $direction and an expected result. Commented Oct 30, 2015 at 10:21
  • Post the value of $direction too. Along with expected output Commented Oct 30, 2015 at 10:24

2 Answers 2

1

try this one

$search = array('0','1','2','3','4','5','6','7','8');
$replace = array('0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9','0-9');
$dir = str_replace($search, $replace, $direction);

and then work around for 9 which depends on your string mine was 0123456789 so I tried $dir = str_replace('99', '9,0-9', $dir);

its working on mine

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, you set me on the way to fing out the solution. I changed fist $dir to $direct $dir = str_replace('99', '9,0-9', $dir); to $dir = str_replace('0-9-9', '0-9', $direct); :)
1

It's explained in the documentation of str_replace():

Caution

Replacement order gotcha

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

You pass arrays as first two arguments to str_replace(). This is the same as you would call str_replace() repeatedly for each element in the array.

If $direction is not '9' then it replaces it with '0-9'. Then, on the last cycle it replaces '9' from '0-9' with '0-9' (according to the values you passed it).


I would drop the code after the first line and read the first sentence again: "get first number and replace it with 0-9".

If your goal is to get the first character of $query_row["Band"] and replace it with 0-9 if it is a digit (and make it uppercase otherwise) I would write something more simple:

$direction = substr($query_row["Band"], 0, 1);

if (is_numeric($direction)) {
    $dir = '0-9';
} else {
    $dir = strtoupper($direction);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.