PHP - 如何检查字符串是否包含任何文本

Che*_*ead 72 php

<?php
$a = '';

if($a exist 'some text')
    echo 'text';
?>
Run Code Online (Sandbox Code Playgroud)

假设我有上面的代码,如何编写语句"if($ a exists'some text')"?

Dai*_*Dai 158

使用该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";
}
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

if( strpos( $a, 'some text' ) !== false ) echo 'text';
Run Code Online (Sandbox Code Playgroud)

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

  • `false> = 0`.你必须把`!== false`写成`0 == false`. (5认同)
  • 而`stripos()`用于**不敏感的**字符串比较... (3认同)

Ble*_*der 16

空字符串是假的,所以你可以写:

if ($a) {
    echo 'text';
}
Run Code Online (Sandbox Code Playgroud)

虽然如果您询问该字符串中是否存在特定的子字符串,您可以使用它strpos()来执行此操作:

if (strpos($a, 'some text') !== false) {
    echo 'text';
}
Run Code Online (Sandbox Code Playgroud)

  • 另外如果你想让它找到"Some Text","SOME TEXT"等,请使用`stripos`(不区分大小写) (4认同)

Lee*_*ish 6

http://php.net/manual/en/function.strpos.php 我认为如果字符串中存在“某些文本”,您会感到奇怪吗?

if(strpos( $a , 'some text' ) !== false)
Run Code Online (Sandbox Code Playgroud)