1

This is the very first time I am trying to use regular expressions, so please have patience.

I would like to use php preg_replace function to transform a string such as this:

"r1=r2+robby+ara"

into

"ar1b=ar2b+robby+ara"
  • so for every occurrence of "r" followed by an integer, I want to place an "a" before it and "b" after it.

I have figured out the search part, but not the replace part - the question-mark below indicates where I am having troubles. Is there a way to "remember" the integer found by [0-9] and use it in replace string?

$s="r1=r2+robby + ara";

$s1=preg_replace ( "/r[0-9]/","ar?b",$s);

Thank you

3 Answers 3

1

You were close, but need parentheses:

$s="r1=r2+robby + ara";
$s1=preg_replace ( "/r([0-9])/","ar$1b", $s); // produces ar1b=ar2b+robby + ara

The ( and ) tell PHP to capture whatever is in between (the digit). The $1 in the replacement tells PHP to use that value (the digit) in that location.

Note: if your problem really is this simple, you don't need parentheses and can use $0, which means "the entire matching portion," like in xdazz's answer:

$s1=preg_replace ( "/r[0-9]/","a$0b", $s); // produces ar1b=ar2b+robby + ara
Sign up to request clarification or add additional context in comments.

Comments

1
// \0 means the matched part
$s1 = preg_replace('/r\d/', 'a\0b', $s);

Comments

1

I'd do:

$str_out = preg_replace('/\b(r\d)\b/', 'a$1b', $str_in);

\b is a word boundary, it prevents, in this case, the replacement of xr1y

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.