本文介绍了匹配第一个单词,然后用 PHP 从字符串中删除它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的字符串:

If I have a string like this:

$subject = "This is just a test";

我想找到第一个单词,然后从 PHP 中的 $subject 中删除它.我使用 preg_match 来获取第一个单词,但我可以使用 单一操作 来删除它吗?

I want to find the first word then remove it from $subject in PHP. I use preg_match to get the first word but can I use a single operation to also remove it?

preg_match('/^(\w+)/', trim($subject), $matches);

在匹配我的第一个单词后,字符串应该是

After matching my first word the string should be

$subject = "is just a test";

$matches 应该包含第一个单词

and $matches should contain the first word

推荐答案

Preg_match 可以捕获,preg_replace 可以替换.我会使用 preg_replace_callback, http://php.net/manual/en/function.preg-replace-callback.php,用于存储您的值并替换原始值.我还稍微修改了您的正则表达式,如果您发现更好,可以将其换回 \w.这将允许该行以 - 和 0-9 开头,但不一定是一个单词.

Preg_match can capture, preg_replace can replace. I'd use the preg_replace_callback, http://php.net/manual/en/function.preg-replace-callback.php, to store your value and replace the original. I also modified your regex a bit you can swap it back to the \w if you find that is better. That will allow the line to start with - and 0-9 as well though so no necessarily a word.

<?php
$subject = "This is just a test";
preg_replace_callback('~^([A-Z]+)\s(.*)~i', function($found) {
        global $subject, $matches;
        $matches = $found[1];
        $subject = $found[2];
    }, $subject);
echo $subject . "\n";
echo $matches;

输出:

只是一个测试
这个

这篇关于匹配第一个单词,然后用 PHP 从字符串中删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:48