在 PHP 的文本中搜索代码


Search codes in a Text in PHP

我想在文本中找到"代码",这些代码可以包含字母和数字,并且可以有不同的长度。文本可能如下所示:

This is a example text, it contains different codes like this one 8de96217e0fd4c61a8aa7e70b3eb68 or that one a7ac356448437db693b5ed6125348.

如何以正确的顺序(从第一个到最后一个)找到并回显它们。我认为有一种方法可以使用 prey_match(),但我不知道如何制作正则表达式。附加信息:代码的长度约为 30 个字符,仅包含较低的字母和数字。

任何帮助真的非常感谢。谢谢!

preg_match_all("/[a-z0-9]{25,}/", $text, $matches);
print_r($matches);

简单,但应该适合您的情况。

输出:

Array
(
    [0] => Array
        (
            [0] => 8de96217e0fd4c61a8aa7e70b3eb68
            [1] => a7ac356448437db693b5ed6125348
        )
)

您可以使用以下代码:

$string = "This is a example text, it contains different codes like this one 8de96217e0fd4c61a8aa7e70b3eb68 or that one a7ac356448437db693b5ed6125348."
preg_match_all("/[0-9a-z]{30,}/", $string, $matches)

其中$matches是包含所有匹配项的数组。如果需要,可以将 {30,} 调整为更大或更小的数字。这只是连续字符的数量。

基本上,

$words = explode($text);
foreach($words as $word)
{
  if(strlen($word)==30)
    echo $word;
}

如果你想消除像#+$*这样的字母...你应该使用正则表达式

编辑:Forlan07的答案显然更好。

如果你的要求是"哈希"同时有字母和数字,你可以尝试类似这样的东西:

$string = "This is a example text, it contains different codes like this one 8de96217e0fd4c61a8aa7e70b3eb68 or that one a7ac356448437db693b5ed6125348.";
$words = explode(" ", $string);
$hashes = array();
foreach ($words as $currWord)
{
    $hasLetter = false;
    $hasNumber = false;
    for ($index = 0; $index < strlen($currWord); $index++)
    {
        if (ctype_alpha($string[$index]))
            $hasLetter = true;
        else
            $hasNumber = true;
    }
    if ($hasLetter && $hasNumber)
        $hashes[] = $currWord;
}