【问题标题】:How find words and strip the words after it?如何找到单词并剥离它之后的单词?
【发布时间】:2015-03-21 03:57:11
【问题描述】:
$string = 'hello world php is a bla bla..';

如何保留'hello world php',通过查找字符串是否包含任何'is',然后删除它后面的所有字符?

我不能使用 substr,因为 'is' 的出现不一致,它也可能是可重复的。第一个怎么抓?

【问题讨论】:

  • 给出更多源字符串和目标字符串的例子。你的问题很模糊(“'is'的出现并不一致,也可能是可重复的”???)
  • @colminator 表示它可能是'hello asp hello is my mom and also is etc',你可以看到'is'出现了两次......
  • 所以对于“hello asp hello is my mom and is etc”,您想将其映射到“hello asp hello”。对吗?

标签: php string substring


【解决方案1】:

你可以使用explode:

<?php

$string = 'hello world php is a bla bla..';

$string = explode(' is ', $string);

echo $string[0];

?>

阅读更多:

http://php.net/manual/en/function.explode.php

【讨论】:

  • 如果我的字符串不包含'is'怎么办? $string = $string[0] 会返回错误吗?
  • @JamesLemon 不,返回原始 $string 。试试代码
  • @AdrianCidAlmaguer 是否适合检查大量检查?例如,除了“是”之外,我也没有其他词......
  • @EltonJamie 是的,试试你的其他话 ;-)
  • @AdrianCidAlmaguer 我的意思是如果我有多个单词会是什么样子。
【解决方案2】:

试试这样,

$string = 'hello world php is a bla bla..';
    $str= substr($string, 0, strpos($string, "is"));

你也可以使用 preg_replace,

$str = preg_replace('/ is.*/', '', $string );

【讨论】:

  • strpos 如果没有找到字符串,可以返回false
  • 为什么'is'后面有一个点?如果我想使用的词是“壮举”怎么办?然后加两个点?圆点是干什么用的?
  • '/is.*/' 这部分告诉 get string after "is".
  • @EltonJamie 点是一个特殊的正则表达式符号,它匹配任何字符 * 匹配任何字符中的 0 个或多个。所以“is.*”基本上意味着,匹配第一个“is”之后的任何内容之后的所有内容。然后那个“匹配”被第二个参数('')替换 - 所以基本上所有在“是”之后的东西 - 包括“是”都被删除了。
  • 我明白了,如果我有多个单词而不是单独的 'is' 怎么办?并且有些单词在后面包含点,例如“壮举”..
猜你喜欢
  • 2022-01-04
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
相关资源
最近更新 更多