PHP 删除第一次出现数字之前的所有内容的脚本
PHP script to remove everything before the first occurrence of a number
我试图在函数中第一次出现数字(如 (1-9))之前删除字符串中的所有数据?
示例:
$value = removeEverythingBefore($value, '1-10');
所以如果我有这样的测试 "Hello I want to rule the world in 100 hours or so"
我希望它找到第一次出现的数字 1
并删除它之前的所有内容。
留给我100 hours or so
。
您可以将 preg_replace
与正则表达式 /([a-z\s]*)(?=\d)/i
一起使用,如下所示:
$string = "Hello I want to rule the world in 100 hours or so";
$newString = preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
echo $newString; // Outputs "100 hours or so"
您可以看到它与 this eval.in 一起工作。如果你想在一个函数中使用它,你可以使用这个:
function removeEverythingBeforeNumber($string)
{
return preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
}
$newString = removeEverythingBeforeNumber("Hello I want to rule the world in 100 hours or so");
您可以使用 strpos to get the index of the first occurence and then substr 获取从该索引开始的字符串。我相信 faster/more 硬件友好然后是正则表达式。
如果你想调用你在 post 中提到的函数,你可以像下面那样做:
<?php
function removeEverythingBefore($value, $pattern) {
preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE);
$initialPosition = $matches[0][1];
return substr($value, $initialPosition);
}
$value = "Hello I want to rule the world in 100 hours or so";
$value = removeEverythingBefore($value, '/[0-9]/');
echo $value; // prints 100 hours or so
这样您也可以使用相同的函数来匹配其他模式。
我试图在函数中第一次出现数字(如 (1-9))之前删除字符串中的所有数据?
示例:
$value = removeEverythingBefore($value, '1-10');
所以如果我有这样的测试 "Hello I want to rule the world in 100 hours or so"
我希望它找到第一次出现的数字 1
并删除它之前的所有内容。
留给我100 hours or so
。
您可以将 preg_replace
与正则表达式 /([a-z\s]*)(?=\d)/i
一起使用,如下所示:
$string = "Hello I want to rule the world in 100 hours or so";
$newString = preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
echo $newString; // Outputs "100 hours or so"
您可以看到它与 this eval.in 一起工作。如果你想在一个函数中使用它,你可以使用这个:
function removeEverythingBeforeNumber($string)
{
return preg_replace("/([a-z\s]*)(?=\d)/i", "", $string);
}
$newString = removeEverythingBeforeNumber("Hello I want to rule the world in 100 hours or so");
您可以使用 strpos to get the index of the first occurence and then substr 获取从该索引开始的字符串。我相信 faster/more 硬件友好然后是正则表达式。
如果你想调用你在 post 中提到的函数,你可以像下面那样做:
<?php
function removeEverythingBefore($value, $pattern) {
preg_match($pattern, $value, $matches, PREG_OFFSET_CAPTURE);
$initialPosition = $matches[0][1];
return substr($value, $initialPosition);
}
$value = "Hello I want to rule the world in 100 hours or so";
$value = removeEverythingBefore($value, '/[0-9]/');
echo $value; // prints 100 hours or so
这样您也可以使用相同的函数来匹配其他模式。