Jump to content

remove spaces withing quotes


micah1701

Recommended Posts

I've used regex a bit in the past with great success but I'm a little stumped on how to do something.

I basically need to do a preg_replace withing another regex.

 

I Need to replace the spaces between words with under_score characters, but only for spaces within quotes, not for all the spaces in the string.

 

In other words, I need this:

Here is a long "test string that" also contains quotes. It actually has "multiple quotes"

to look end up looking like this:

Here is a long "test_string_that" also contains quotes. It actually has "multiple_quotes"

 

could someone point me in the best direction?

thanks!

Link to comment
https://forums.phpfreaks.com/topic/203087-remove-spaces-withing-quotes/
Share on other sites

You can use preg_replace_callback.

 

$str = 'Here is a long "test string that" also contains quotes. It actually has "multiple quotes"';

$newstr = preg_replace_callback(
    '~"(.+?)"~',
    create_function(
        '$match',
        'return str_replace(" ", "_", $match[0]);'
    ),
    $str
);

echo $newstr;

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.