Strip punctuation with PHP

PHPServer Side ProgrammingProgramming

The ‘preg_replace’ function can be used to match the characters in the string and remove the unnecessary characters.

To keep letters and numbers −

Example

Live Demo

<?php
$s = "Hello, my name is Bobby !? I am 8 years !"; print_r( preg_replace('/[^a-z0-9]+/i', ' ',$s));
?>

Output

This will produce the following output −

Hello my name is Bobby I am 8 years

To keep letters only −

Example

Live Demo

<?php
$s = "Hello, my name is Bobby !? I am 8 years !"; print_r( preg_replace('/[^a-z]+/i', ' ',$s));
?>

Output

This will produce the following output −

Hello my name is Bobby I am years

To keep letters, numbers and underscore

Example

<?php
$s = "Hello, my name is Bobby !? I am 8 years !"; print_r(preg_replace('/[^w]+/', ' ',$s));
?>

Output

This will produce the following output −

Hello my name is Bobby I am 8 years
Published on 09-Apr-2020 14:28:08