nkspartan
nkspartan

Reputation: 485

REGEX (in PHP).. remove non-alphanumeric characters at ends?

$test = "!!!   sdfsdf   sd$$$fdf   ___";
$test = str_replace(' ', '_', $test); // Turn all spaces into underscores.
echo $test."<br />"; // Output: !!!___sdfsdf___sd$$$fdf______

$test = preg_replace('/[^a-zA-Z0-9_-]/', '-', $test); // Replace anything that isn't alphanumeric, or _-, with a hyphen.
echo $test."<br />"; // Output: !!!___sdfsdf___sd---fdf______

$test = preg_replace('/([_-])\1+/', '$1', $test); // Reduce multiple _- in a row to just one.
echo $test."<br />"; // Output: !_sdfsdf_sd-fdf_

The above code is what I currently have, what I'm trying to figure out the REGEX for is how to cut off any non-alphanumeric characters off the ends. So turning the final output from "!_sdfsdf_sd-fdf_" to "sdfsdf_sd-fdf".

Upvotes: 1

Views: 2648

Answers (4)

Gumbo
Gumbo

Reputation: 655219

You can replace your whole code with this:

$test = preg_replace('/[^a-zA-Z0-9]+/', '_', $test);
$test = trim($test, '_');

The first will replace all occurrences of one or more illegal characters with _ and the second will rmove any remaining _ from the start and end.

Upvotes: 2

Kaivosukeltaja
Kaivosukeltaja

Reputation: 15735

[a-zA-Z0-9].*[a-zA-Z0-9]

Meaning: Read any alphanumeric character, then read as much of anything as we can, making sure we can get at least one alphanumeric character at the end.

Upvotes: 1

Greg
Greg

Reputation: 321588

You can use trim():

$test = trim($test, '_-');
echo $test;

The "!" won't make it past the first regular expression.

Upvotes: 2

user187291
user187291

Reputation: 53940

  $clean = preg_replace('~(^[^a-z0-9]+)|([^a-z0-9]+$)~i', '', $str);

Upvotes: 3

Related Questions