elmas
elmas

Reputation: 69

How to Remove Space Additionally to the Special Chars?

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

Upvotes: 2

Views: 539

Answers (4)

Don Kirkby
Don Kirkby

Reputation: 56230

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);

Upvotes: 2

pestilence669
pestilence669

Reputation: 5699

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"); ?>

Upvotes: 1

codaddict
codaddict

Reputation: 455440

Try:

<?php

$str = '"yo! here"';

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

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

?>

Upvotes: 3

leepowers
leepowers

Reputation: 38318

You can remove any non-words:

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

Upvotes: 0

Related Questions