0

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

2
  • humm... can you give an example of a sentence? Commented Feb 7, 2013 at 20:20
  • preg_replace is acceptable, but I can't figure out how to use it correctly to do what I need Commented Feb 7, 2013 at 20:20

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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?

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.