[英]Regex match that must contain all characters in a string
I'm sure this has already been asked and answered, but I honestly couldn't find my answer after searching for quite a bit and reading Regex Tutorial . 我确定已经有人问过并回答了这个问题,但老实说,经过大量搜索并阅读了Regex Tutorial之后,我找不到我的答案。 What I'm looking to do is match a string that has the same characters and length as another string. 我想做的是匹配一个具有与另一个字符串相同的字符和长度的字符串。 For example, a string "abcde" would match "edcba" but would not match "abcdf" or "aabbc" or "abc" . 例如,字符串“ abcde”将匹配“ edcba”,但将不匹配“ abcdf”或“ aabbc”或“ abc” 。
Here is my test code with the closest I've come up with that uses a character class, but what I can't figure out is how to get regex to basically iterate through each character in the class once starting at the beginning of the match string: 这是我使用的最接近的使用字符类的测试代码,但是我不知道的是一旦比赛开始,如何使regex基本上遍历该类中的每个字符串:
$string = 'abcde';
$array = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match)
{
if (preg_match("/[$string]/i",$match))
echo "TRUE -> $match";
else
echo "FALSE -> $match";
}
Which gives the result: 结果如下:
TRUE -> edcba
TRUE -> eeeee
FALSE -> fghij
TRUE -> fedcba
FALSE -> qqq
TRUE -> cbaed
TRUE -> cba
When what I really want is: 当我真正想要的是:
TRUE -> edcba
FALSE -> eeeee
FALSE -> fghij
FALSE -> fedcba
FALSE -> qqq
TRUE -> cbaed
FALSE -> cba
Basically you are checking for anagrams . 基本上,您正在检查字谜 。 Why not sort the strings and compare for equality? 为什么不对字符串排序并比较相等性呢?
$string = 'abcde';
$string = str_sort($string); // sort the string.
$array = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match) {
$match = str_sort($match); // sort each match.
if (strcmp($match,$string) == 0) // now string compare.
echo "TRUE -> $match\n";
else
echo "FALSE -> $match\n";
}
function str_sort($string) {
// function to sort a string..not the best but works :)
$tmp = str_split($string);
sort($tmp);
return implode('',$tmp);
}
I'm not sure you would want to use Regex in this. 我不确定您是否要在此使用Regex。 I think you'll want to use a plain old find statement for all your letters. 我想您会希望对所有字母使用简单的旧find语句。
作为使用正则表达式的替代方法,您可以将每个字母转换为一个字符,然后对其进行排序,并检查两个字符是否相等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.