【问题标题】:how to check if some characters are in an string? [duplicate]如何检查某些字符是否在字符串中? [复制]
【发布时间】:2017-09-09 13:59:16
【问题描述】:

我们有一个类似的字符串:

$string="Lorem Ipsum is simply dummy text of the printing and typesetting industry.";

所以我想检查该字符串中是否有可用的单词。例如:

$words=['Ipsum','54'];

你可以看到Ipsum在字符串中但54不在字符串中,所以函数应该回调true(因为找到了Ipsum)。 我正在使用php,感谢您的帮助。

【问题讨论】:

  • *** $words = array('Ipsum','54');
  • 自己创建一个函数并将strpos放入其中
  • 你应该使用 strpos,对 $words 数组运行 foreach() 并在 foreach 中使用 strpos。
  • 查看侧边栏中的this 问题。

标签: php


【解决方案1】:

一个简单的循环结合strpos 应该是你实现这一目标所需要的全部

function containsOneOfThoseWords($str, $words) {
    foreach ($words as $word) {
        if (strpos($str, $word) !== false) return true;
    }
    return false;
}

【讨论】:

  • 感谢您的帮助,但看到此代码:ali98.xyz/filter.txt,它不起作用!
  • @AliYQB 你应该将参数传递给函数...containsOneOfThoseWords($str, $words)
【解决方案2】:
php > $string="Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
php > $lookfor = "simply";
php > echo strpos($string, $lookfor) > 0 ? true : false ;
1
php > $lookfor = "simplest";
php > echo strpos($string, $lookfor) > 0 ? true : false ;
//nothing will be printed -))

只需从 sn-p 上面创建一个函数。

更新

$ cat search.php
<?php

$domain="asdasd asd fasdfasfafafad f454   asdfa";
$lookfor=array('as','f454');

function containsOneOfThoseWords($str, $words) {
    foreach ($words as $word) {
        if (strpos($str, $word) !== false) return true;
    }
    return false;
}

echo containsOneOfThoseWords($domain, $lookfor);
?>
$ php search.php; echo 
1

【讨论】:

  • strpos 也可以返回0,如果搜索词位于0 位置,这完全可以——您应该检查false 而不是&gt; 0
  • 是的,没错-))
  • 感谢您的帮助,但看到此代码:ali98.xyz/filter.txt,它不起作用!
  • 您应该将参数传递给您的containsOneOfTheseWords 函数。我已修复它 - 请参阅我的更新答案。
猜你喜欢
  • 1970-01-01
  • 2011-03-31
  • 2016-08-21
  • 1970-01-01
  • 2016-08-09
  • 2020-11-01
  • 2014-05-07
  • 2010-11-22
相关资源
最近更新 更多