Brad
Brad

Reputation: 12262

php regular expression find and replace

$string = '20110306';
$pattern = '(\d{6})(\d{2})';
$replacement = '$101';
echo preg_replace($pattern, $replacement, $string);

I want it to echo 20110301

I used http://gskinner.com/RegExr/ to come up with the search and replacement pattern, maybe I am missing something when it comes to replacing the found pattern.

It gives me the following warning:

Message: preg_replace() [function.preg-replace]: Unknown modifier '('

Upvotes: 1

Views: 347

Answers (2)

codaddict
codaddict

Reputation: 455020

Two changes:

  1. You need to place the regex between a pair delimiters, say / as::

    $pattern = '/(\d{6})(\d{2})/';
    
  2. $101 refers to group number 101. You meant to append 01 to group number 1 so change

    $replacement = '$101';
    

    to

    $replacement = '${1}01';
    

See it

Upvotes: 5

powtac
powtac

Reputation: 41050

replace the () by ~~ in $pattern.

Upvotes: 0

Related Questions