0

I am new to regular expressions in php.

I am trying to replace values something like

101_1
102_2
103_3

to word "custom values" in my strings

I have tried many combinations but could not find solution. Here is the code I think should work according to documentation of regular expressions help available on internet

$result = str_replace('[1-6]*_1', "custom values", $string);

Remember these values come in between the string, nor in start neither in end of string.

4
  • 1
    Are the xxx_x numbers always the same length/format?
    – l'L'l
    Jan 23, 2014 at 1:55
  • 1
    [1-6] means a digit between 1 and 6. Now guess what should be used instead of 1 at the end
    – HamZa
    Jan 23, 2014 at 1:55
  • 1
    Oh, I get it ... You're using the wrong function. You should be using preg_replace()
    – HamZa
    Jan 23, 2014 at 2:00
  • 1
    @HamZa, Thanks — I switch between two many regexes sometimes to remember the escapes, which is kind of important. :)
    – l'L'l
    Jan 23, 2014 at 2:05

3 Answers 3

1

Your expression doesn't work because it is not capturing the 0 in [1-6].

Assuming you always have an underscore between one or more digits, use:

$result = preg_replace('/\d+_\d+/', "custom values", $string);
1

Try something such as this:

$result = preg_replace('/\d{3}_\d/', "custom values", $string);

it captures the first three digits followed by the underscore and then another digit.

1

use preg_replace instead of str_replace

preg_replace('/[0-6]{1,3}_[1-3]/', 'custom values', $string);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.