Q:

PHP program to remove special characters from a string

belongs to collection: PHP String Programs

0

Characters other than alphabets and numbers are called special characters. And they can have used more than one which is doesn't happen in the case of alphabets or numbers.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

1) Using preg_replace()

This is the most used method. A pattern can be inputted which will be replaced everywhere in the string.

preg_replace() function can be used in PHP for searching and replacing. It always returns either a string or an array, according to what was searched and replaced.

Syntax:

    preg_replace(
        $word_to_replace, 
        $new_word, 
        $string_to_be_searched, 
        $limit, 
        $count
        )

In the given example we have a sentence from which every special character including space is removed,

Program:

<?php
    #string
    $str = 'We welcome all of you to our school (of PHP).
    This--> school is one of its kind :).
    Many schools dont offer this subject :(';
    
    $str = preg_replace('/[^A-Za-z0-9]/', '', $str);
    
    // Printing the result
    echo $str;
?>

Output:

WewelcomeallofyoutoourschoolofPHPThisschoolisoneofitskindManyschoolsdontofferthissubject

2) Using str_replace()

This is not common but it has its own importance. This differs from the first method in the sense that here programmer defines the special characters. He also decides what should the special characters be replaced with if the program encounters it.

str_replace() function is used for searching a regular expression and replacing a specific content in place of all the occurrences of searched expression. It always returns either a string or an array, according to what was searched and replaced. It has three mandatory parameters while one is optional. The compulsory parameters of the function are - value to be searched, the value it will be replaced with and the string in which this value needs to be searched. The optional parameter specifies the count of the number of times the replacement is needed.

Syntax:

    str_replace(
        $word_to_replace, 
        $new_word, 
        $string_in_which_word_is_present
        )

Program:

<?php
    #string 
    $str= 'We, welcome all of you, to our school <of PHP>.
    This--> school is one of its kind :).
    Many schools dont offer this subject :(';

    $str = str_replace( array( '\'', '(',')', ',' , ':', '<', '>','.',' ','-' ), '',$str); 

    // Printing the result 
    echo $str;  
?>

Output:

WewelcomeallofyoutoourschoolofPHP
Thisschoolisoneofitskind
Manyschoolsdontofferthissubject

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< PHP | Count the total number of words in a string...