如果我有这样的字符串:
$subject = "This is just a test";
我想找到第一个单词,然后在PHP中从$subject
中删除它。我使用preg_match
来获取第一个字,但是我可以使用单个操作来删除它吗?
preg_match('/^(\w+)/', trim($subject), $matches);
匹配我的第一个单词后,字符串应为
$subject = "is just a test";
和$matches
应包含第一个单词
答案 0 :(得分:1)
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;
输出:
只是一个测试
这
答案 1 :(得分:1)
与chris'的答案一样,我的方法依赖于子串中至少有2个单词由单个空格分隔的事实。
代码:(Demo)
$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()
一样:
代码:(Demo)
$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