Marty Wallace
Marty Wallace

Reputation: 35796

Regex to replace spaces and brackets with underscore

I have some strings in the following formats:

this is a string
This is a string
This is a (string)
This is a  string

and i want a regex convert it to the following:

this_is_a_string

with no leading

I have the following using preg_replace which is getting me almost all of the way:

preg_replace('/[^A-Za-z]+/', '_', $string)

However, it converts the last ) to an underscore which is not acceptable for my uses. I could easily trim that off in a separate function but im wondering if its possible to do with a single regex?

Upvotes: 1

Views: 3179

Answers (3)

Enissay
Enissay

Reputation: 4953

$result = preg_replace('~([^a-zA-Z\n\r()]+)~', '_', $string);

Try it HERE

Be sure tehre's no trailing or leading spaces in your string or it will be replaced too... Use trim($string) to remove it

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149078

Regular expressions are a great tool, but there are some things they're not well suited for. Converting the case of characters is one thing regular expressions alone can't do. You could use the preg_replace_callback function to transform the matched text to lowercase, but this is actually pretty straight forward to accomplish by simply changing your logic around a bit.

Perhaps something like this instead:

$string = 'This is a (string)';
preg_match_all("/[a-zA-Z]+/", $string, $matches);
$string = strtolower(implode('_', $matches[0])); // this_is_a_string

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

$result = preg_replace('~[^A-Z]+([A-Z]+)(?:[^A-Z]+$)?~i', '_$1', $string);

Upvotes: 2

Related Questions