简体   繁体   English

如何检查字符串是否在Php中包含确切的子字符串

[英]How to check if a string contains an exact substring in Php

I am trying to check if a number say 1 is present in a string say 11,12,13 To do this I am using strpos : 我正在尝试检查说11,12,13的字符串中是否存在数字说1 ,我正在使用strpos

<?
$s = "2,3,11,12,13";
$ss = "1";
if(strpos($s, $ss)) echo "success";
else echo "fail";
?>

Here I am expecting the code to give fail as output but it gives success . 在这里,我期望代码以fail作为输出,但可以success Is there any function I can use to exactly match the number in a string. 我可以使用任何函数来完全匹配字符串中的数字吗? I want the number 1 in the string, not the numbers containing 1 like 11,123,100 etc. 我要的号码1在字符串中,不包含数字111,123,100等。

Edit 1: It works fine for @Twinfriends answer but the problem is doing it with multiple numbers. 编辑1:它适用于@Twinfriends答案,但问题是使用多个数字。

<?
    $s = "2,3,11,12,13";
    $ss = "1,2";
    if(strpos($s, $ss)) echo "success";
    else echo "fail";
    ?>

This code gives output fail but it should give true. 此代码使输出fail但应为true。

Edit 2: Check answer https://stackoverflow.com/a/48297002/8490014 编辑2:检查答案https://stackoverflow.com/a/48297002/8490014

The problem has been solved but because of for each loop the output is getting repeated as many times as there are values in the array. 这个问题已经解决了,但是由于每个循环,输出重复的次数与数组中的值一样多。 How can we get the output repeating the output? 如何使输出重复输出?

You could do it like this: 您可以这样做:

<?php

$s = "2,3,11,12,13";
$ss = "1";

$toTest = explode(",", $s);

if(in_array("$ss", $toTest)) {
    echo "success";
}
else {
    echo "fail";
}

?>

If you've any question considering this code, feel free to ask. 如果您对此代码有任何疑问,请随时提出。 (Code tested, works well) (经过测试的代码,效果很好)

The problem has been solved by adding a foreach loop: 通过添加一个foreach循环已解决了该问题:

<?
$s = "2,3,11,12,13";
$ss = "1,2,3,5";

$catid = explode(",", $s);
$ocat = explode(",",$ss);

    foreach($ocat as $abc) {
if(in_array($abc, $catid)) {
 echo "success";
}
else {
echo "fail";
}
}
?>

Try this: 尝试这个:

<?php
$s = "2,3,11,12,13";
$ss = "1";

$haystack = explode(",",$s);
$matches  = preg_grep ("/$ss/", $haystack);

echo !empty($matches) ? "success" : "fail";

You can check by appending comma after the variable to check occurrence at start , appending comma before the variable to check occurrence at last or appending comma before and after the variable to check occurrence at middle . 您可以通过检查appending commavariable在检查发生startappending comma的前variable在检查发生lastappending comma前和后variable在检查发生的middle

if((substr($s, 0, (strlen($ss)+1)) === $ss.',')||(substr($s, (strlen($s)-strlen($ss)-1), strlen($s)) === ','.$ss)||(strpos($s, ','.$ss.','))){
        echo "success";
}
else{
        echo "fail";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM