【问题标题】:Finding an occurence of a string after a certain string在某个字符串之后查找字符串的出现
【发布时间】:2014-07-17 15:11:43
【问题描述】:

我正在尝试检测电子邮件的优先级(以纯文本形式存储在变量中),每封电子邮件都有一个“cmets”部分,我希望在其中搜索“紧急”或“高”等术语cmets 区域,但没有其他地方,因为这些术语在其他地方。

到目前为止,我一直在做的是:

if (stristr($body, 'Comment: urgent')){
    $urgent = true;
    echo '<b>Urgent.</b>';
}

显然,这不适用于“紧急”出现在“这很紧急”这样的句子中的情况。

如何在子字符串 "Comment:" 之后搜索 $body?

谢谢!

【问题讨论】:

标签: php regex string preg-match substring


【解决方案1】:

你可以使用正则表达式:

<?php

$string = 'rweiuowreuiwuier Comment: higewrwre werwrewre high';

if (preg_match('#Comment: (urgent|high)#i',$string)){
    $urgent = true;
    echo '<b>Urgent.</b>';
}

但是你应该考虑如果有人把Comment: high这个邮件放在body里面也会被认为是高的

【讨论】:

  • 好电话,但很多人倾向于尽可能避免使用正则表达式,因此我的解决方案,请参阅答案;仍然投票,因为它是一个功能答案。
【解决方案2】:

以下函数 - 可以使用新名称,需要三个参数。

$a being the Start Frame
$b being the End Frame
$s being the full string

$a would be 'Comment: '
$b would be whatever is at the end of your comments section
$s would be the email string

返回值将是中间的字符串,然后在返回值上运行您的 stripos。

function getMiddle($a, $b, $s) {
    return strstr(substr($s, strpos($s, $a) + strlen($a)), $b, true);
}

示例:#注意,第二个参数需要专门用于您的电子邮件#

if (stripos(getMiddle('Comments: ', 'Sincerely', $email), 'urgent') === false) {
    echo "URGENT";
}

【讨论】:

  • 幸运的是,我有这个是为了满足自己的需要,只需要为自己进行最低限度的修改:D
【解决方案3】:

你可以用函数strpos找到一个字符串

    $mystring = 'Comment: urgent';
    $find_string   = 'urgent';
    $pos = strpos($mystring, $find_string);

if ($pos !== false) {
     echo "I find it!";
} else {
     echo "Not found";
}

【讨论】:

  • 这并没有回答他应该如何仅从Comment: 第四次检测,因此不是一个正确的答案。因为他的字符串不仅仅是Comment: urgent
  • 但他想在“评论:”字符串上找到紧急。
  • 不,'Comment:' 是字符串的一部分,他想在该部分之后而不是之前找到 URGENT。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2023-02-25
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
相关资源
最近更新 更多