gpt4 book ai didi

php - 如何检查字符串是否包含特定文本

转载 作者:IT老高 更新时间:2023-10-28 12:01:06 25 4
gpt4 key购买 nike

<?php
$a = '';

if($a exist 'some text')
echo 'text';
?>

假设我有上面的代码,语句if($a exist 'some text')怎么写?

最佳答案

使用 strpos 函数:http://php.net/manual/en/function.strpos.php

$haystack = "foo bar baz";
$needle = "bar";

if( strpos( $haystack, $needle ) !== false) {
echo "\"bar\" exists in the haystack variable";
}

在你的情况下:

if( strpos( $a, 'some text' ) !== false ) echo 'text';

请注意,我使用 !== 运算符(而不是 != false== true 甚至只是 if( strpos( ... ) ) {) 是因为 "truthy"/"falsy" PHP 处理 strpos 的返回值的性质。

从 PHP 8.0.0 开始,您现在可以使用 str_contains

<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always
return true";
}

关于php - 如何检查字符串是否包含特定文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15305278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com