PHP preg_replace question

Status
Not open for further replies.

ziycon

New Member
The below line will remove all alphanumeric characters, what I'm trying to do is remove all alphanumeric characters but replace all spaces with '-'. Will I just need to have two preg_replace statements or can it be done in the one line?
Code:
[COLOR=#0000bb]preg_replace[/COLOR][COLOR=#007700]([/COLOR][COLOR=#dd0000]“/[^a-zA-Z0-9\s]/”[/COLOR][COLOR=#007700], [/COLOR][COLOR=#dd0000]“”[/COLOR][COLOR=#007700], [/COLOR][COLOR=#0000bb]$string[/COLOR][COLOR=#007700])[/COLOR]
So this line:
Test data's - "testing"
would become:
Test-datas-testing
 

php.allstar

New Member
Hi, try this:

PHP:
<?php

     $string = 'Test data\'s - "testing" ';
     
     $patterns = array();
     $patterns[0] = '/[^a-zA-Z0-9\s]/';
     $patterns[1] = '/\s+/';

     $replacements = array();
     $replacements[0] = '';
     $replacements[1] = '-';
     
     echo preg_replace($patterns, $replacements, trim($string));

?>
there's probably a more eloquent way to get rid of the trailing whitespace with a modifier as opposed to using trim() but I can't think of it at this moment!

Patterns and replacements can be sent as indexed arrays instead of strings as I've demonstrated here.
 

php.allstar

New Member
ah yes, that trailing whitespace issue was annoying me so I had to find the solution! Try this instead:

PHP:
<?php

     $string = 'Test data\'s - "testing" ';
     
     $patterns = array();
     $patterns[0] = '/[^a-zA-Z0-9\s]|\s$/';
     $patterns[1] = '/\s+/';

     $replacements = array();
     $replacements[0] = '';
     $replacements[1] = '-';
     
     echo preg_replace($patterns, $replacements, $string);

?>

Added |\s$ to the first pattern to match the trailing whitespace as well as non alphanumeric characters
 

php.allstar

New Member
Glad to have helped! Please click the "Thanks" link under my post as seeing it makes me feel all warm and fuzzy!
 
Status
Not open for further replies.
Top