user1022585
user1022585

Reputation: 13651

php string replace/remove

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.

Upvotes: 1

Views: 261

Answers (4)

DaveRandom
DaveRandom

Reputation: 88657

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.

Upvotes: 1

dimme
dimme

Reputation: 4424

You can do that using explode:

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

Upvotes: 0

codaddict
codaddict

Reputation: 455072

You can do:

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

See it

Upvotes: 1

Tom van der Woerdt
Tom van der Woerdt

Reputation: 29975

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 (

Upvotes: 0

Related Questions