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
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;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.