Matt Urtnowski
Matt Urtnowski

Reputation: 2566

Replace numbers in string with phrase-number

In PHP I have a string with a value of something like 1 OR 2 or maybe 1 AND (20 OR 3). I would like to replace those numbers with a phrase followed by the number to make something like condition1 meaning:

1 OR 2 => condition1 OR condition2

1 AND (20 OR 3) => condition1 AND (condition20 OR condition3)

I think I can use preg_replace to do this but I can't figure out how. I'm having a difficult time preserving the value of the numbers during the replacement.

If it makes it easier I will also accept an answer in javascript

Upvotes: 0

Views: 147

Answers (2)

M K Garwa
M K Garwa

Reputation: 495

you can use str_replace($search, $replace, $string)

$search can be array whatever you want to replace
$replace can alse be an array wherever you want to replace in a string
$string is a string where you want to change

is it solution of your problem or you want something else?

Upvotes: 1

nickb
nickb

Reputation: 59709

If the arguments to the operators are the only numbers in the string, you can do:

$new = preg_replace( '/(\d+)/', 'condition$1', $input);

This matches any successive number of digits, and captures them in a capturing group, which we reference later in the replacement as $1.

You can see from this demo that for your test cases, this outputs:

condition1 OR condition2
condition1 AND (condition20 OR condition3)

Upvotes: 3

Related Questions