Open In App

How to remove Punctuation from String in PHP ?

Last Updated : 29 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Punctuation removal is often required in text processing and data cleaning tasks to prepare the text for further analysis or display.

Below are the methods to remove punctuation from a string in PHP:

Using preg_replace with a Regular Expression

In this approach, we are using the preg_replace function with a regular expression to match the pattern and remove punctuation characters from the string. The regular expression /[\p{P}]/u is used to match the punctuation character in the string. The preg_replace function replaces these matched characters with an empty string.

Syntax:

preg_replace( $pattern, $replacement, $string )

Example: The below example uses preg_replace with a regular expression to match and remove the punctuation from the string.

PHP
<?php
    // Original string
    $string = "Hello, Geek! How are you?";
    
    // Remove punctuation using regular expression
    $clean_string = preg_replace('/[\p{P}]/u', '', $string);
    
    echo $clean_string;
?>

Output
Hello Geek How are you

Using str_replace function

In this approach, we use str_replace to remove punctuation. Here, we create an array of punctuation characters, which is then passed to the str_replace function to remove them from the string. The str_replace function replaces each punctuation character in the array with an empty string, effectively removing them from the string.

Syntax:

str_replace($punctuation_array, '', $string);

Example: The below example uses str_replace to remove the Punctuation from String.

PHP
<?php
    // Input string with punctuation
    $string = "Welcome to GeeksForGeeks,! How are you?";

    // Remove punctuation characters
    $clean_string = str_replace(['.', ',', '!', '?'], '', $string);

    echo $clean_string;

?>

Output
Welcome to GeeksForGeeks How are you

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads