精易论坛

标题: 问下php如果寻找文本命令怎么使用。 [打印本页]

作者: 虾王    时间: 2025-2-3 20:25
标题: 问下php如果寻找文本命令怎么使用。
比如,我循环文本$val中是含有sck文字,如果有返回执行A命令,没有执行B命令,在易语言是如果(寻找文本),在PHP调用什么函数呀,希望给个例子。

作者: lxtyzh    时间: 2025-2-3 21:14
[PHP] 纯文本查看 复制代码
$text = "这是一个示例文本";
$keyword = "示例";

if (strpos($text, $keyword) !== false) {
    echo "找到了";
} else {
    echo "未找到";
}

作者: 经典奶茶    时间: 2025-2-3 21:18


deepseek吧   chat.deepseek.com

作者: CigaretteWine    时间: 2025-2-4 00:21
strpos 函数 记得用=== 或!== 强制必须同类型false
因为0也是false 而0 也有可能是第一个位 所以必须强制恒等于
作者: qq977352880    时间: 2025-2-4 16:30
关注一下,期待更多讨论。

作者: cobi    时间: 2025-2-5 09:36
PHP 寻找字符串
在PHP中,寻找字符串可以通过多种方式实现,这取决于你具体的需求,比如是查找一个子串在另一个字符串中的位置,还是检查一个字符串是否包含另一个字符串等。下面是一些常用的方法:

1. 使用 strpos() 函数
strpos() 函数用于查找字符串的首次出现位置。
[PHP] 纯文本查看 复制代码
$string = "Hello, world!";
$findMe = "world";
$pos = strpos($string, $findMe);

if ($pos === false) {
    echo "The string '$findMe' was not found in the string.";
} else {
    echo "The string '$findMe' was found in the string.";
    echo " and exists at position $pos.";
}


2. 使用 stripos() 函数
stripos() 函数与 strpos() 类似,但它不区分大小写。

[PHP] 纯文本查看 复制代码
$string = "Hello, world!";
$findMe = "WORLD";
$pos = stripos($string, $findMe);

if ($pos === false) {
    echo "The string '$findMe' was not found in the string.";
} else {
    echo "The string '$findMe' was found in the string.";
    echo " and exists at position $pos.";
}


3. 使用 strstr() 或 stristr() 函数
这些函数用于查找字符串的首次出现并返回从该位置到字符串末尾的所有字符。stristr() 版本不区分大小写。

[PHP] 纯文本查看 复制代码
$string = "Hello, world!";
$findMe = "world";
$part = stristr($string, $findMe);

if ($part !== false) {
    echo "The string '$findMe' was found in the string.";
    echo " and the rest of the string is: $part";
} else {
    echo "The string '$findMe' was not found in the string.";
}


4. 使用 str_contains() 函数(PHP 8.0+)
从PHP 8.0开始,可以使用str_contains()函数来检查一个字符串是否包含另一个字符串。这个函数返回一个布尔值。

[PHP] 纯文本查看 复制代码
$string = "Hello, world!";
$findMe = "world";
if (str_contains($string, $findMe)) {
    echo "The string '$findMe' was found in the string.";
} else {
    echo "The string '$findMe' was not found in the string.";
}


5. 使用 mb_strpos() 函数(多字节支持)
对于多字节字符集(如UTF-8),可以使用mb_strpos()函数。这个函数提供了对多字节字符的正确支持。

[PHP] 纯文本查看 复制代码
$string = "你好,世界!"; // 注意这里的字符不是简单的ASCII字符,而是UTF-8编码的汉字。
$findMe = "世界";
$pos = mb_strpos($string, $findMe);

if ($pos === false) {
    echo "The string '$findMe' was not found in the string.";
} else {
    echo "The string '$findMe' was found in the string.";
    echo " and exists at position $pos.";
}


选择合适的方法取决于你的具体需求,比如是否需要考虑大小写、是否需要返回位置还是直接返回子串等。






欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4