Reputation: 25038
Having strings like
$s1 = "Elegan-71";
$s2 = "DganSD-171";
$s2 = "SD-1";
what would be the best way to delete all chars from '-' to end like
$cleans1 = "Elegan";
$cleans2 = "DganSD";
$cleans2 = "SD";
There is substr($s1, "-",4);
substr(string $string, int $start, int[optional] $length=null);
but how to tell that it should remove all numbers and how to know numbers size as they are variable?
Upvotes: 1
Views: 76
Reputation: 1548
i like :
$cleans1 = strtok($s1, "-");
about strtok
Upvotes: 1
Reputation: 2556
ststr can does it too.
$s1 = "Elegan-71";
$clean = strstr($s1, '-', true);
echo $clean;
Upvotes: 1
Reputation: 917
Assuming you are cleaning each string individually, and you don't want to end up with neither an array or a list, and that each string ends up in that pattern (dash and number), this should do the trick:
$cleans1 = preg_replace('/-\d+$/', '', $s1);
Upvotes: 1
Reputation: 2776
This will do what you want:
<?php
$my_string = "happy-123";
$hyphen_position = strrpos($my_string, '-');
$fixed_string = substr($my_string, 0, $hyphen_position);
echo $fixed_string;
?>
Upvotes: 1
Reputation: 61
$s1 = "Elegan-71";
if (strrpos($s1, '-')){
$cleans1 = substr($s1, 0, strrpos($s1, '-'));
}else{
$cleans1 = $s1;
}
That should do the trick.
Upvotes: 1