strstr

虽然 Strstr 可以用于相同的目的,但 PHP 手册不鼓励使用它,指出 strpos 既更快又使用更少的内存:

如果我们只想确定特定的针是否出现在 haystack 中,请改用速度更快、内存占用更少的函数 strpos()。

使用 strstr 类似于使用 strpos:

if (false !== strstr($source_str, $substring)) {
  echo 'Found!';
} else {
  echo 'Not found!';
}

strchr 是 strstr 的别名

使用strpos函数

如果未找到子字符串,strpos 函数将返回 false,如果找到,则返回表示其位置的数值。
这就是我们使用“!==”运算符的原因,大致意思是“不等于”。
值“0”也将被理解为 false,因此进行“!=”比较将不起作用。
然而,"!==" 操作符可以让 PHP 进行精确的比较。

$source_str = 'beamer@onitroad.com';
$substring = '@';
if (false !== strpos($source_str, $substring)) {
  echo 'Found it';
} else {
  echo "Not found!";
}

如果在 $source_str 中找到 $substring 并且它位于开头(第 0 个位置),它将返回该位置。
因此我们使用 "!==" 或者 "<>" 作为比较运算符:

$source_str = 'beamer@onitroad.com';
$substring = '@';
if (false !== strpos($source_str, $substring)) {
  echo 'Found it';
} else {
  echo "Not found!";
}

strpos 不区分大小写版本是stripos。

使用正则表达式

当我们需要匹配字符串中的多个部分时,我们可以使用正则表达式(regex 或者 regexp)。
它们有用的地方之一是当我们想要验证来自提交表单的用户输入时。

要使用正则表达式,我们可以使用 preg_match 函数。

下面是一个非常简单的匹配,也可以使用 stripos 来执行:

if (preg_match("/neeDle/i", "There's a small needle in a haystack")) {
    echo "Found!";
} else {
    echo "Not found!";
}

模式 /neeDle/i 末尾的 i 使正则表达式执行不区分大小写的匹配,因此在上述情况下,带有小写字母的“needle”将被匹配。

有一个更高级的函数,preg_match_all,它允许我们处理字符串中的所有匹配项。
例如,一个地方是有用的,当我们处理 HTML 文档时,我们希望找到某种类型的所有标签,比如标题 (h1-h6)。

我们可以使用它为文章创建“目录”列表,使用标题作为链接上的锚文本。
在下面的示例中,我将展示这是如何完成的。

$table_of_contents = '';

$source_string = '<body> code here....
<h1 id="section1">Some HTML fragment</h1>
<p>Example paragraph</p>
<h2 id="section2">Subsection to h1</h2>
<p>Second example paragraph</p>
<h2 id="section3">Subsection to h2</h2>
<p>Third example paragraph</p>';

preg_match_all("|<h[^>]+>(.*)</h[1-6]+>|i",
    $source_string,
    $headings, PREG_SET_ORDER);

$match_count = count($headings);
for ($i = 0; $i < $match_count; $i++) {
  $table_of_contents .= "\n ". '<li><a href="#section'.$i.'">' . $headings["$i"][1] . '</a></li>';
}
$table_of_contents = '<ol>' . $table_of_contents . "\n". '</ol>';
echo $table_of_contents;

"\n" 创建一个换行符。

使用 PHP 检查字符串是否包含子字符串

可以通过多种方式在 PHP 中执行 if 字符串包含检查,最好的方法之一是使用 strpos() ,但也可以使用正则表达式检查更复杂的模式。

我们需要在另一个字符串中找到一个字符串的常见情况是在验证电子邮件时。
我们可以使用 strpos 检查是否存在“@”字符,或者我们可以创建一个正则表达式来执行更复杂的验证。
PHP 具有用于电子邮件验证的内置方法,因此创建自己的方法可能是个坏主意。

下面是使用 strpos 进行的简单检查:

if (false !== strpos('string contains PHP', 'PHP')) {
  echo 'PHP was found in string';
} else {
  echo "Not found!";
}

从 PHP 8 开始,我们可以使用 str_contains 函数:

if (str_contains('string contains PHP', 'PHP')) {
  echo 'PHP was found in string';
}
日期:2020-06-02 22:16:48 来源:oir作者:oir