Jump to content

Is there a way to do this in one go?


joe92

Recommended Posts

I wish to extract the data between the square brackets and replace the spaces with underscores in one go?

E.g. I have the string

location=[location to go to]

 

I need to get it to,

location_to_go_to

 

Currently I am using a preg_replace_callback with a str_replace to change the spaces into underscores, but it seems like a long winded route to take. Is there a way I can do this in one clean sweep of a preg_replace?

 

Here is the existing code:

<?php
function removeSpace($match){
$string = $match[1];
$string = str_replace(' ', '_', $string);
return $string;
}	
$location = 'location=[location to go to]';
echo $location.'<br/>into<br/>';
$location = preg_replace_callback("~location=\[([\w\s-]+)\]~ism", "removeSpace", $location);
echo $location;

 

If not, then I suppose it's no great loss. I'm just constantly looking for ways to improve my regex skills :D

 

Cheers,

Joe

Link to comment
Share on other sites

Hi Joe,

 

You don't know the number of spaces (if any) in the string, is that right? If so, your preg_replace_callback combined with a str_replace or preg_replace looks great to me.

 

If you know the number of spaces, you can do it with a single preg_replace, but you probably know that. ;)

 

Wishing you a fun weekend.

 

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.