简体   繁体   English

REGEX(在PHP中)..删除末尾的非字母数字字符?

[英]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. 上面的代码是我目前拥有的代码,我想弄清楚REGEX的目的是如何截断所有非字母数字字符。 So turning the final output from "!_sdfsdf_sd-fdf_" to "sdfsdf_sd-fdf". 因此,将最终输出从“!_sdfsdf_sd-fdf_”变为“ sdfsdf_sd-fdf”。

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

You can use trim() : 您可以使用trim()

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

The "!" “!” won't make it past the first regular expression. 不会超过第一个正则表达式。

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. 第一个将所有出现的一个或多个非法字符替换为_ ,第二个将从头到尾删除所有剩余的_

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

含义:读取任何字母数字字符,然后尽我们所能读取尽可能多的东西,确保最后可以得到至少一个字母数字字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM