Remove unwanted characters in a string

12,262

Solution 1

Your regex is invalid...

$str = 'Â 4:30am';
$new_string = preg_replace("~[^a-z0-9:]~i", "", $str); 
echo '<pre>'.$new_string.'</pre>';

... and you forgot ":" in the regex, so in your case it will be removed.

Solution 2

Your regex pattern needs to be enclosed by delimiters. Your current pattern is using the [ and ] as the delimiters, which most likely isn't what you intended to do.

preg_replace("/[^A-Za-z0-9]/", "", $str); 

http://pl.php.net/manual/en/regexp.reference.delimiters.php

Solution 3

You can use filter_var

$str = 'Â 4:30am';
$str = filter_var($str,FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH);
echo $str ;

Output

4:30am

Solution 4

Use $new_string = preg_replace("/[^A-Za-z0-9]/", "", $str); should fix it.

The first parameter of preg_replace is the pattern, which is required to be surrounded by something like / or @.

In your case, you're using the pattern [^A-Za-z0-9] where [ and ] are treated as pattern delimiters. So the actual pattern being matched becomes ^A-Za-z0-9, which matches nothing in the input.

Solution 5

To get the time:

$str = 'Â 4:30am';
$time = preg_match('/(?P<time>\d?\d:\d\d(?:am|pm))/', $str, $match);
var_dump($match);
Share:
12,262
Vainglory07
Author by

Vainglory07

Updated on June 04, 2022

Comments

  • Vainglory07
    Vainglory07 almost 2 years

    I would like to ask how to remove a special character from a string(extracted from a scrapped page).

    Â 4:30am
    

    I just want to get the time so ive tried so filter it using this:

    $str = 'Â 4:30am';
    $new_string = preg_replace("[^A-Za-z0-9]", "", $str); 
    echo '<pre>'.$new_string.'</pre>';
    

    But it doesn't change :| Is there any solution/approach?

  • dev-null-dweller
    dev-null-dweller over 11 years
    It was enclosed in delimiters :) See third example from linked manual and sentence above it.