Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Strip punctuation with PHP
In PHP, you can strip punctuation from strings using the preg_replace() function with regular expressions. This function allows you to match specific character patterns and replace them with desired characters or remove them entirely.
Keep Letters and Numbers Only
To remove all punctuation while keeping alphabetic characters and digits ?
<?php
$s = "Hello, my name is Bobby !? I am 8 years !";
echo preg_replace('/[^a-z0-9]+/i', ' ', $s);
?>
This will produce the following output −
Hello my name is Bobby I am 8 years
Keep Letters Only
To remove punctuation and numbers, keeping only alphabetic characters ?
<?php
$s = "Hello, my name is Bobby !? I am 8 years !";
echo preg_replace('/[^a-z]+/i', ' ', $s);
?>
This will produce the following output −
Hello my name is Bobby I am years
Keep Letters, Numbers, and Underscores
To preserve word characters (letters, digits, and underscores) while removing punctuation ?
<?php
$s = "Hello, my name is Bobby_123 !? I am 8 years !";
echo preg_replace('/[^\w]+/', ' ', $s);
?>
This will produce the following output −
Hello my name is Bobby_123 I am 8 years
Using trim() for Clean Results
Combine preg_replace() with trim() to remove extra spaces at the beginning and end ?
<?php
$s = "!!!Hello, world???";
$clean = trim(preg_replace('/[^a-z0-9]+/i', ' ', $s));
echo "'" . $clean . "'";
?>
This will produce the following output −
'Hello world'
Conclusion
The preg_replace() function with appropriate regular expressions provides flexible control over punctuation removal. Use /[^a-z0-9]+/i for alphanumeric characters, /[^a-z]+/i for letters only, and /[^\w]+/ for word characters including underscores.
