【问题标题】:php file search without special characters [duplicate]没有特殊字符的php文件搜索[重复]
【发布时间】:2021-05-28 10:13:13
【问题描述】:

我正在尝试使用此代码执行 php 搜索:

$search = &q;
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
  if(strpos($line, $search) !== false)
  {
    $found = true;
    echo $line;
  }
}
// If the text was not found, show a message
if(!$found)
{
  echo '';

它搜索每个字符并且有时返回而没有结果。我想将此代码设置为仅搜索字母和数字,但不包含任何特殊字符,包括点和逗号。我该怎么做? 谢谢。

【问题讨论】:

  • $search = &q; 应该会抛出错误。您可以使用正则表达式来执行此操作。你有没有尝试过?
  • 你没有给出任何$line 的例子或者你想从中得到什么,那么别人怎么知道你想要什么?

标签: php search special-characters


【解决方案1】:

基本:

// $search contains query
// remove non-alphanumeric characters from search query
$search = preg_replace('[^a-zA-Z\d\s:]','',$search); 

// Get unfiltered file into an array
$original_lines = file('file.txt');

$num_matches = 0;
foreach ($original_lines as $line) {

      if(strpos(preg_replace('[^a-zA-Z\d\s:]','',$line), $search) !== false){
         $num_matches++;
         echo $line;
      }
}

if (!$num_matches){
   echo "No matches.";
}

实验性的,可能内存和处理效率低下:

// $search contains query
// remove non-alphanumeric characters from search query
$search = preg_replace('[^a-zA-Z\d\s:]','',$search); 

// Get unfiltered file into an array
$original_lines = file('file.txt');

// Read entire file to string, filtering non-alphanumeric characters
$filtered_lines = preg_replace('[^a-zA-Z\d\s:]','',implode("\n",$original_lines); 

// Count the matches
if ($num_matches = preg_match_all($search,$filtered_lines,$matches)){

   // Convert back to array with replacements
   $filtered_lines = explode('\n',$filtered_lines); 

   $found_lines = 0; $line_index = -1;
   foreach ($filtered_lines as $fline) {

      $line_index++;

      if(strpos($fline, $search) !== false)
      {
         $found_lines++;

         echo $original_lines[$line_index];
      }

      if ($found_lines == $num_matches){
         break; // No more matches, so stop processing additional lines
      }
   }
}
else{
   echo "No matches...";
}

【讨论】:

  • 很好的解决方案!非常感谢!
猜你喜欢
  • 2011-08-02
  • 1970-01-01
  • 1970-01-01
  • 2021-08-11
  • 2016-05-30
  • 1970-01-01
  • 2011-04-23
  • 1970-01-01
  • 2019-09-03
相关资源
最近更新 更多