匹配第一个单词,然后用PHP将其从字符串中删除
如果我有这样一个字符串:匹配第一个单词,然后用PHP将其从字符串中删除,php,regex,Php,Regex,如果我有这样一个字符串: $subject = "This is just a test"; 我想找到第一个单词,然后将其从PHP中的$subject中删除。我使用preg_match来获取第一个单词,但是我可以使用单个操作来删除它吗 preg_match('/^(\w+)/', trim($subject), $matches); 匹配我的第一个单词后,字符串应该是 $subject = "is just a test"; 而$matches应该包含第一个单词Preg\u match可
$subject = "This is just a test";
我想找到第一个单词,然后将其从PHP中的$subject
中删除。我使用preg_match
来获取第一个单词,但是我可以使用单个操作来删除它吗
preg_match('/^(\w+)/', trim($subject), $matches);
匹配我的第一个单词后,字符串应该是
$subject = "is just a test";
而
$matches
应该包含第一个单词Preg\u match
可以捕获,Preg\u replace
可以替换。我会使用preg\u replace\u回调
,存储您的值并替换原始值。我还对正则表达式进行了一些修改,如果您觉得更好,可以将其换回\w
。这将允许行以-和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的答案一样,我的方法依赖于这样一个事实,即子字符串中至少有两个单词由单个空格分隔
代码:()
或者您可以更简单地使用这一行:
list($first,$subject)=explode(' ',$subject,2); // limit the number of matches to 2
或
或
如果您出于某种疯狂的原因特别需要正则表达式解决方案,preg\u split()
的工作原理与explode()
:
代码:()
那么你被困在如何删除第一个单词?(可能preg\u replace()
?!)使用preg\u replace匹配/捕获单词,并将其替换为空字符串…preg\u replace如何存储找到的匹配项?它返回新字符串,而不是我的匹配项。我不想只删除第一个单词,还想知道它是什么is@all你已经在你的问题中做了那部分了,这就是问题所在。我不喜欢那里的global
,但我能做什么呢?谢谢另外,我是否需要PHP5.3用于preg\u replace\u callback
?您可以通过使用use()
引用传递$matches
,只需将返回值:preg\u replace\u callback
分配给$subject
,然后您就可以删除:全局…
@ali^查看我的评论;由于匿名函数,您需要PHP5.3
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);
$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