匹配第一个单词,然后用PHP从字符串中删除它


Match first word then remove it from string with PHP

如果我有一个这样的字符串:

$subject = "This is just a test";

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

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

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

$subject = "is just a test";

$matches应该包含第一个字

Preg_match可以捕获,preg_replace可以替代。我会使用preg_replace_callback, http://php.net/manual/en/function.preg-replace-callback.php,来存储您的值并替换原始值。我也修改了你的正则表达式一点,你可以交换回'w,如果你发现这是更好的。这将允许行以- and 0-9开头,尽管不一定是单词。

<?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;
输出:

只是一个测试

就像chris的回答一样,我的方法依赖于这样一个事实,即子字符串中至少有两个单词由一个空格分隔。

代码(演示):

$subject = "This is just a test";
$halves=explode(' ',$subject,2);  // create a two-element(maximum) array
$first=array_splice($halves,0,1)[0];  // assign first element to $first, now $halves is a single, reindexed element
$subject=$halves[0];
echo "First=$first and Subject=$subject";
// output: First=This and Subject=is just a test

或者您可以更简单地使用这一行代码:

list($first,$subject)=explode(' ',$subject,2);  // limit the number of matches to 2

echo "First=",strstr($subject,' ',true)," and Subject=",ltrim(strstr($subject,' '));

echo "First=",substr($subject,0,strpos($subject,' '))," and Subject=",substr($subject,strpos($subject,' ')+1);

如果你因为一些疯狂的原因特别想要一个正则表达式解决方案,preg_split()就像explode():

代码(演示):

$subject = "This is just a test";
list($first,$subject)=preg_split('/ /',$subject,2);  // limit the number of matches to 2
echo "First=$first and Subject=$subject";
// output: First=This and Subject=is just a test