Horje
How to remove Punctuation from String in PHP ?

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



Reffered: https://www.geeksforgeeks.org


PHP

Related
Common Mistakes to Avoid in PHP Common Mistakes to Avoid in PHP
How to find Sum the Digits of a given Number in PHP ? How to find Sum the Digits of a given Number in PHP ?
How to Extract Words from given String in PHP ? How to Extract Words from given String in PHP ?
How to get the POST values from serializeArray in PHP ? How to get the POST values from serializeArray in PHP ?
PHP Program to Reverse Bit of a Number PHP Program to Reverse Bit of a Number

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18