【问题标题】:Finding a part of a text from symbol to symbol从符号到符号查找文本的一部分
【发布时间】:2012-02-05 12:27:05
【问题描述】:

例如我有文字。

$text = 'Hello dear friend, my name is Jacky.
I am 25 years old and @I am earning* $500 per month, but @I am going* to earn more';

我想查找文本中以符号“@”开头并以符号“*”结尾的所有部分。 在这个例子中,我想要这样的变量:

$found[1] = 'I am earning';
$found[2] = 'I am going';

谁能帮我解决这个问题?我使用 strstr(),但是当找到多个部分时它会失败。

【问题讨论】:

  • 你应该很快得到一个令人满意的答案,但这是通过 preg_match 完成的。我不记得正则表达式的确切语法,因此是评论。
  • “谁能帮我解决这个问题?”。 Stack Overflow 不是导师招聘场所。请提出一个具体问题,向我们展示您尝试过的东西。
  • 我建议您展示您的代码,以便有人可以向您展示如何将其扩展到多个匹配项。这样你会学到更多……

标签: php text symbols strstr


【解决方案1】:

使用preg_match_all()

$text = 'Hello dear friend, my name is Jacky. I am 25 years old and @I am earning* $500 per month, but @I am going* to earn more';
preg_match_all("/(?<=@).*?(?=\*)/", $text, $found);

匹配项将存储在$found

【讨论】:

    【解决方案2】:
    preg_match_all('/@(.*?)\*/', $str, $matches);
    $matches = $matches[1];
    

    或者:

    preg_match_all('/(?<=@).*?(?=\*)/', $text, $matches);
    $matches = $matches[0];
    

    两者都导致$matches 相等:

    Array
    (
        [0] => I am earning
        [1] => I am going
    )
    

    【讨论】:

    • 你可能想让那些@/* 成为断言。他不希望它们出现在结果中。
    • $found = $matches[0];回声$找到; // 结果“数组”;
    • @pzztzz:它是一个数组,你不能简单地echo它。
    • Tim Cooper 我如何回应第一和第二?
    • @pzztzz: echo $matches[0] , "&lt;br /&gt;", $matches[1];
    猜你喜欢
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2014-04-11
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多