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
https://forums.phpfreaks.com/topic/255935-is-there-a-way-to-do-this-in-one-go/
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.

 

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.