Search code examples
regexreplacepreg-replaceexpressionregular-language

Replacement in regular expression


I have a list:

1  name1
2  name2
3  name3

I need to replace all 1,2,3... to '1', '2', '3'...and name1, name2, name3 to 'name1', 'name', 'name'3. I know how to do it via '\n' and '\s'.

But I think the better way exists. Does anybody know this way?


Solution

  • Heres a little snippet in PHP:

    $str = "1 name1\n2 name2\n3 name3";
    $str2 = preg_replace('!([^\s]+)\s([^\n]+)!sm', "'$1' '$2'", $str);
    echo $str2;
    

    It uses $1 and $2 to reference the rounded bracket you 'catched' in the string