Replace part of string between quotes in php regex

徘徊边缘 提交于 2019-12-06 04:49:32

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:

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

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"

If you don't need to use regular expressions, here is an iterative version that works:

<?php
    function remove_quoted_whitespace($str) {
        $result = '';
        $length = strlen($str);
        $index = 0;
        $in_quotes = false;

        while ($index < $length) {
            $c = $str[$index++];

            if ($c == '"') {
                $in_quotes = !$in_quotes;
            } else if ($c == ' ') {
                if ($in_quotes) {
                    continue;
                }
            }

            $result .= $c;
        }

        return $result;
    }

    $input = '"mission podcast" modcast A B C "D E F"';
    $output = remove_quoted_whitespace($input);

    echo $input . "\n";
    echo $output . "\n";
?>

The entire foreach is not needed at all! It is possible to use a one-liner for this.

Here is the code which replaces spaces in quoted strings. The idea is that if a space is inside quotes, it is followed by odd number of quotes. It can be done by regexp look-ahead.

echo preg_replace('{\s+(?!([^"]*"[^"]*")*[^"]*$)}',"x",$str);

That's all! How it works? It matches all \s characters which are not followed by even number of quotes. The matching spaces get replaced by x. You can of course change it to any desired value or leave it empty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!