Php 如何执行这两个功能?
可以在正则表达式中执行这两个函数转换吗Php 如何执行这两个功能?,php,regex,Php,Regex,可以在正则表达式中执行这两个函数转换吗 // Get all alpha-substring to left and before of any digits // otherwise return empty string. function ex1($source) { $string_alpha = ""; $tmp = substr($source, 0, strcspn($source, '0123456789')); if (ctype_alpha($tmp)) {
// Get all alpha-substring to left and before of any digits
// otherwise return empty string.
function ex1($source) {
$string_alpha = "";
$tmp = substr($source, 0, strcspn($source, '0123456789'));
if (ctype_alpha($tmp)) {
$string_alpha = $tmp;
}
return $string_alpha;
}
// Get all numeric-substring to right and after last letter
// otherwise return empty string.
function ex2($source) {
$string_numeric = "";
$tmp = substr($source, strcspn($source, '0123456789'));
if (ctype_digit($tmp)) {
$string_numeric = $tmp;
}
return $string_numeric;
}
$source = "butterfly12";
echo "ex1 function => " . ex1($source) . "<br>";
echo "ex2 function => " . ex2($source) . "<br>";
// Output:
// ex1 function => butterfly
// ex2 function => 12
我试着用这两个例子来编码我需要做的事情。
非常感谢。用于在函数中捕获它们
用于捕获字母的正则表达式:
/[A-Z]+/i
用于捕获数字的正则表达式:
/[0-9]+/
所以你可以有如下功能:
function getAlpha($source) {
preg_match("/([A-Z]+)/i", $source, $matches);
return $matches[1];
}
function getNumeric($source) {
preg_match("/([0-9]+)/", $source, $matches);
return $matches[1];
}
你可以这样使用它:
echo getAlpha("butterfly12"); //butterfly
echo getNumeric("butterfly12"); //12
编辑
我现在想我明白你的意思了,也许这些功能对你最有效:
function getAlpha($source) { //Gets whatever text is before a number.
$alpha = "";
if(preg_match("/^([A-Z]+)\d+/i", $source, $matches)) {
$alpha = $matches[1];
}
return $alpha;
}
function getNumeric($source) { //Gets whatever number is after the text.
$numeric = "";
if(preg_match("/(\d+)$/", $source, $matches)) {
$numeric = $matches[1];
}
return $numeric;
}
对到目前为止你们有什么?谢谢,我知道这一点,但在两个例子中,我并没有简单地捕获一个子串,而是用特定的条件来验证它。为此我问了。我更新了我的例子。该代码将按预期工作。它无法正常工作。例如,如果字符串以数字开头,函数ex1返回空字符串,getAlpha返回Alpha字符串。验证失败。Me不需要简单地提取数字/字母字符串。再次感谢。那你想要什么?如果字符串以数字开头,那么怎么办?如果它以字符串开头,那又怎样?请讲清楚,否则我帮不上忙。我想知道,如果可能的话,在正则表达式中精确地转换ex1和ex2函数,它的工作方式与work ex1和ex2函数一样。为了更准确,我写了两个函数就是为了这个原因。因此,它更适合正则表达式。ex1和ex2函数不仅捕获字母子字符串或数字子字符串,还进行验证。