1
$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 '('

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

replace the () by ~~ in $pattern.

1 Comment

or indeed, any other valid regex delimiter character.

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.