Search code examples
phpregexsubstringquotesdouble-quotes

Replace part of string between quotes in php regex


Now I've got very basic regex skills, only used regex a couple of times for basic stuff. This has probably been asked before, which I apologize for, but I couldn't find any answer for this. Found similar, though and tried to adapt it but to no avail. OK, to the question - How do I replace a space only between certain characters (doublequotes in this case)?

Say i have the following string:

"mission podcast" modcast A B C "D E F"

I want to replace the spaces between mission and podcast as well as the ones between D, E & F whilst leaving the other ones untouched.

P.S. What if space was a string? An example for that is welcome as well.

Edited this a bit I hope now it's more clear. Edit 2: I need to do this on a string in php and execute it in the shell. Edit 3: I'm sorry i changed the whole question 3 times it's just i'm getting quite confused myself. Cheers!


Solution

  • Description

    I would attack this problem by first splitting the string into groups of either quoted or not quoted strings.

    Then iterating through the matches and if Capture Group 1 is populated, then that string is quoted so just do a simple replace on replace Capture Group 0. If Capture group 1 is not populated then skip to the next match.

    On each iteration, you'd want to simply build up a new string.

    Since splitting the string is the difficult part, I'd use this regex:

    ("[^"]*")|[^"]*

    enter image description here

    Example

    Sample Text

    "mission podcast" modcast A B C "D E F"
    

    Code

    PHP Code Example: 
    <?php
    $sourcestring="your source string";
    preg_match_all('/("[^"]*")|[^"]*/i',$sourcestring,$matches);
    echo "<pre>".print_r($matches,true);
    ?>
    

    Capture Groups

    $matches Array:
    (
        [0] => Array
            (
                [0] => "mission podcast"
                [1] =>  modcast A B C 
                [2] => "D E F"
                [3] => 
            )
    
        [1] => Array
            (
                [0] => "mission podcast"
                [1] => 
                [2] => "D E F"
                [3] => 
            )
    
    )
    

    PHP Example

    This php script will replace only the spaces inside quoted strings.

    Working example: http://ideone.com/jBytL3

    Code

    <?php
    
    $text ='"mission podcast" modcast A B C "D E F"';
    
    preg_match_all('/("[^"]*")|[^"]*/',$text,$matches);
    
    foreach($matches[0] as $entry){
        echo preg_replace('/\s(?=.*?")/ims','~~new~~',$entry);
        }
    

    Output

    "mission~~new~~podcast" modcast A B C "D~~new~~E~~new~~F"