Mark
Mark

Reputation: 637

How to strip specific punctuation in a string using php?

I am currently using this function to strip punctuation but it's like an uncontrolable axe murderer.

<?php $search = preg_replace("/[^a-zA-Z 0-9]+/", " ", $search);?>

I want more control on what is been stripped. I would like to keep these characters and letters and numbers ofcourse

/ . , : - ?

Thats all of them I think for now

EDIT:

This is the sql that query's the db

"SELECT c.ARTIST, c.TITLE, c.`CAT NO.`, c.FORMAT, c.`IMAGE PATH` FROM tracklisting t 
RIGHT JOIN catelogue c ON c.`CAT NO.` = t.`TRACKLISTING CAT NO.` 
WHERE t.`ARTIST` LIKE '%$search%' OR t.`TRACK TITLE` LIKE '%$search%'OR c.`ARTIST` LIKE '%$search%' OR c.`TITLE` LIKE '%$search%'"

EDIT:

Many Thanks To everyone, I have it working like a bomb now.

Upvotes: 1

Views: 353

Answers (2)

Mark Byers
Mark Byers

Reputation: 838036

You can simply add those characters to your character class to avoid them being replaced:

preg_replace('#[^a-zA-Z 0-9/.,:?-]+#', " ", $search);
#                          ^^^^^^

A few characters will need to be escaped with a backslash inside the character class otherwise they have a special meaning: your chosen regular expression delimiter, a backslash, a close square bracket, and a hyphen (unless it's at the beginning or end of the character class). Also you will need to escape a quote so that it doesn't terminate the PHP string literal prematurely.

Upvotes: 4

Nick
Nick

Reputation: 6346

Instead of using regex, you could use something like this:

$symbols = array('/','\\','\'','"',',','<','>','?',';',':','[',']','{','}','|','=','+','-','_',')','(','*','&','^','%','$','#','@','!','~','`');

for ($i = 0; $i < sizeof($symbols); $i++) {
    $string = str_replace($symbols[$i],' ',$string);
}

It's a bit easier to understand if your not familiar with regex.

However, there are probably performance downsides doing it this way.

Upvotes: 0

Related Questions