views:

139

answers:

4

Hello, in my functions.php if have this code:

 echo '<a href="' . preg_replace('/\s/', '-', $search) . '-keyword1.html">' . urldecode ($search) . '</a>';

this removes the special chars..

but how can i additonally add remove space and replace it with - and remove "

so, if someone types in "yo! here" i want yo-here

thank you!

A: 

You can remove any non-words:

preg_replace('/\W/', '-', $search);
pygorex1
+2  A: 

If you want to replace a run of unwanted characters with a single dash, then you can use something like this:

preg_replace('/\W+/', '-', $search);

To remove surrounding quotes, and then replace any other junk with dashes, try this:

$no_quotes = preg_replace('/^"|"$/', '', $search);
$no_junk = preg_replace('/\W+/', '-', $no_quotes);
Don Kirkby
For the OP's input: '"yo! here"' this will produce '-yo-here-'
codaddict
Ah, I missed the quote requirement. Updating...
Don Kirkby
+3  A: 

Try:

<?php

$str = '"yo! here"';

$str = preg_replace( array('/[^\s\w]/','/\s/'),array('','-'),$str);

var_dump($str); // prints yo-here

?>
codaddict
+1  A: 

This will replace multiple spaces / "special" chars with a single hyphen. If you don't want that, remove the "+".

You might want to trim off any trailing hyphens, should something end with an exclamation point / other.

<?php preg_replace("/\W+/", "-", "yo! here   check this out"); ?>

Pestilence