我正在过滤电话号码的文字。我的正则表达没问题。过滤器的行为应如下所示:
文字:this is demo number 205five456734
已过滤的文字:this is demo number **********
。 five
应被视为5,应予以阻止。
如果匹配的数字长度> 14,则不应过滤。
在这里,我试过它的工作不会显示带过滤的结果。它没有显示任何错误信息,只显示空白屏幕。
process('this is testing number 2034342345 and this should not be filtered 20334334343443343434',$words); // Ignore $words, there are not being. They are just set of words which we are not using in function
function process($text, $words)
{
// $arrwords = array(0=>'zero',1=>'one',2=>'two',3=>'three',4=>'four',5=>'five',6=>'six',7=>'seven',8=>'eight',9=>'nine');
//Here I want to replace any word digit to zeros of same length
$arrwords = array(0000=>'zero',000=>'one',000=>'two',00000=>'three',0000=>'four',0000=>'five',000=>'six',00000=>'seven',00000=>'eight',0000=>'nine');
//Here I want to replace
preg_match_all('/[A-za-z]+/', $text, $matches);
$arr=$matches[0];
foreach($arr as $v)
{
$v = strtolower($v);
if(in_array($v,$arrwords))
{
$text= str_replace($v,array_search($v,$arrwords),$text);
}
}
//return $text;
$resultSet = array();
$l = strlen($text);
/*if($l>14)
echo $text;
*/
foreach ($words as $word){
$pattern = '/^(?:\((\+?\d+)?\)|(\+\d{0,3}))? ?\d{2,3}([-\.]?\d{2,3} ?){3,4}/';
preg_match_all($pattern, $text, $matches, PREG_OFFSET_CAPTURE );
//In above array replace by 0s and here check match size. if > 14 then return text
//I want to check if matching number length is greater then 14 or not, if yes then dont filter it and return original text
/*if(strlen($matches)>14)
{
return $text;
}*/
$this->pushToResultSet($matches);
}
return $resultSet;
}
答案 0 :(得分:1)
我已经重构了你的代码 - 因为我根本无法理解它,但是这是一种你可以使用的方法,效果非常好:
首先我们创建一个隐藏数字字符串的函数:
function hideNumber($numericValue){
$returnStatement = "";
for($i = 0; $i < strlen((string)$numericValue); $i++){
$returnStatement .= "*";
}
return $returnStatement;
}
然后是过程函数:
function process($text){
//replace any word digit to zeros of same length
$arrwords = array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
$arrvalues = array('0000', '000', '000', '00000', '0000', '0000', '000', '00000', '00000', '0000');
//replacing the ocurrences of numbers one by one
$cleanNumericText = str_replace($arrwords, $arrvalues, $text);
//matching the numbers
$re = '/(?<=[^\d]|^)[\d]{1,14}(?=[^\d]|$)/m';
preg_match_all($re, $cleanNumericText, $occurrences);
//preparing the replacement value for each correct number
$arrHideNumbersValue = array();
foreach($occurrences[0] as $value){
$arrHideNumbersValue[] = hideNumber($value);
}
//replacing the numbers by its correspondent values
$cleanPasswordText = str_replace($occurrences[0], $arrHideNumbersValue, $cleanNumericText);
return $cleanPasswordText;
}
请注意,我没有使用很多foreach (str_replace
可以为您替换数组出现次数)
您正在寻找的正则表达式是this one:(?<=[^\d]|^)[\d]{1,14}(?=[^\d]|$)
,它将匹配1到14个字符的数字。
然后打印出来:
echo "<pre>" . process('this is testing number 203five4342345 and this should not be filtered 20334334343443343434');