如何跳过首个正则表达式比赛? [英] How to skip first regex match?
本文介绍了如何跳过首个正则表达式比赛?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用正则表达式和php时仍然可以跳过第一场比赛.
Is there anyway to skip the first match when using regex and php.
或者有某种方法可以使用str_replace来实现.
Or is there some way of achieveing this using str_replace.
谢谢
更新 我正在尝试从另一个字符串中删除一个字符串的所有实例,但我想保留第一个匹配项,例如
UPDATE I am trying to remove all the instances of a string from another string but I want to retain the first occurance e.g
$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';
输出字符串为:
这是一个测试字符串,用于 test 删除单词 test
This is a test string to test to removing the word test
推荐答案
简便的PHP方式:
<?php
$pattern = "/an/i";
$text = "banANA";
preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
preg_match($pattern, $text, $matches, 0, $matches[0][1]);
echo $matches[0];
?>
会给您"AN".
更新:不知道它是替代品.试试这个:
UPDATE: Didn't know it was a replace. Try this:
<?php
$toRemove = 'test';
$string = 'This is a test string to test to removing the word test';
preg_match("/$toRemove/", $string, $matches, PREG_OFFSET_CAPTURE);
$newString = preg_replace("/$toRemove/", "", $string);
$newString = substr_replace($newString, $matches[0][0], $matches[0][1], 0);
echo $newString;
?>
找到第一个比赛并记住它在哪里,然后删除所有内容,然后将第一个位置中的所有内容放回去.
Find the first match and remember where it was, then delete everything, then put whatever was in the first spot back in.
这篇关于如何跳过首个正则表达式比赛?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文