[need help] PHP script remove unwanted chars

ogah

New member
can somebody help me?
i want to remove unwanted chars in text
eg.
replace 5 stars, 05 stars, 05. stars to stars
05stars replace to 5stars
5stars will not replaced
 

Peter

Member
I think this will do what you want.
Code:
$str = '5 stars, 05 stars, 05. stars, 05stars';
$str = preg_replace('/0?5.? stars/', 'stars', $str); // replace 5 stars, 05 stars, 05. stars to stars
$str = str_replace('05stars', '5stars', $str); // 05stars replace to 5stars
echo $str; // stars, stars, stars, 5stars
 

ogah

New member
thanks Peter, but i mean all number not only 0 & 5
i want remove all leading number if have space betwen number & text
 

ogah

New member
Peter said:
Will this do?
Code:
$str = preg_replace('/\d+.?\d*\s+([^\s]+)/', '$1', $str);
but. number in the middle of text also gone.

so, i modify like this
PHP:
$str = preg_replace('/^\d+.?\d*\s+([^\s]+)/', '$1', $str);
$str = ltrim($str, '0'); //remove leading 0 if not replaced by preg_replace
 

paschim

New member
Regex is definitely the best approach, but for simplicity, you can use array filters too.

PHP:
$str = "05 spac3 9test 9 star 0.5 something";
$tmp_arr = explode(' ',$str);
$new_arr = array_filter($tmp_arr, 'remove_numbers');
$new_str = implode(' ',$new_arr);

function remove_numbers($var){
      return !is_numeric($var);
}
 

ogah

New member
paschim said:
Regex is definitely the best approach, but for simplicity, you can use array filters too.

PHP:
$str = "05 spac3 9test 9 star 0.5 something";
$tmp_arr = explode(' ',$str);
$new_arr = array_filter($tmp_arr, 'remove_numbers');
$new_str = implode(' ',$new_arr);

function remove_numbers($var){
      return !is_numeric($var);
}

thanks paschim, but i dont want like that.
i want "05 spac3 9test 9 star 0.5 something" will be "spac3 9test 9 star 0.5 something"

your script maybe also drainage the server resource if $str is very long words