1

Say I have strings: "Sports Car (45%)", or "Truck (50%)", how can I convert them to "Sports_Car" and "Truck".

I know about str_replace or whatever but how do I clip the brackets and numbers part off the end? That's the part I'm struggling with.

1
  • 1
    Do you always have "String (Int%)" ? Use regular expression... Commented Nov 26, 2011 at 17:33

4 Answers 4

1

You can do:

$s = "Sports Car (45%)";
$s = preg_replace(array('/\([^)]*\)/','/^\s*|\s*$/','/ /'),array('','','_'),$s);

See it

Sign up to request clarification or add additional context in comments.

Comments

1

There are a few options here, but I would do one of these:

// str_replace() the spaces to _, and rtrim() numbers/percents/brackets/spaces/underscores
$result = str_replace(' ','_',rtrim($str,'01234567890%() _'));

or

// Split by spaces, remove the last element and join by underscores
$split = explode(' ',$str);
array_pop($split);
$result = implode('_',$split);

or you could use one of a thousand regular expression approaches, as suggested by the other answers.

Deciding which approach to use depends on exactly how your strings are formatted, and how sure you are that the format will always remain the same. The regex approach is potentially more complicated but could afford finer-grained control in the long term.

Comments

0

A simple regex should be able to achieve that:

$str = preg_replace('#\([0-9]+%\)#', '', $str);

Of course, you could also choose to use strstr() to look for the (

1 Comment

That returns "Sport" instead of "Sport_Car"
0

You can do that using explode:

<?php
$string = "Sports Car (45%)";
$arr = explode(" (",$string);
$answer = $arr[0];
echo $answer;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.