1

I would like to replace each \x to $matches[x] where x is a number.

It works only for predefined numbers with str_replace:

str_replace( array(
    '\\1',
    '\\2',
    '\\3',
    '\\4'
), array(
    '$matches[1]',
    '$matches[2]',
    '$matches[3]',
    '$matches[4]'
), $string );
2
  • 2
    Take a look at preg_repalce() Commented Nov 25, 2015 at 13:16
  • Why can't you create the first argument in a dynamic manner, based on the length of the second argument? Commented Nov 25, 2015 at 13:20

1 Answer 1

1

Use regular expression in preg_replace

Code:

<?php

$str = '\\2 string \\123 gogog \\123 sda \\342 \\3525 wqe \\234';
echo preg_replace('~(\\\\)(\d+)~', '$matches[$2]', $str);

Output:

$matches[2] string $matches[123] gogog $matches[123] sda $matches[342] $matches[3525] wqe $matches[234]
Sign up to request clarification or add additional context in comments.

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.