Michael
Michael

Reputation: 811

preg_replace: How to not remove the whole part?

I got this string:

$string = "hello123hello237ihello523";

I want to search for an "o" followed by a number. Then I want to remove only the "o".

I've been trying:

preg_replace("/kl[0-9]/", "", $string);

The problem is that is removes the number as well. I only want to remove the "o". Any ideas?

Upvotes: 1

Views: 143

Answers (2)

cmbuckley
cmbuckley

Reputation: 42468

You could use back references:

echo preg_replace('/o([0-9])/', '$1', $string);

See the documentation for information on referencing subpatterns.

Upvotes: 0

strkol
strkol

Reputation: 2029

use positive lookahead:

echo preg_replace("/o(?=[0-9])/", "", $string);

For more information: http://www.regular-expressions.info/lookaround.html

One other option is:

echo preg_replace("/o([0-9])/", "\\1", $string);

This will replace the o[number] with [number]

Upvotes: 2

Related Questions