使用PHP中的正则表达式从头开始删除空格

时间:2014-08-18 12:28:47

标签: php regex

我试图使用php curl从网站获取数据。从输出中,我需要忽略所有的空格和空行。我用了一些正则表达式。我真的不熟悉Regex。

请帮我解决这个问题。

有我的代码:

if(preg_match('/<div class="search-results-details-body">(.*?) <div class="search-results-details-footer">/s', $result, $output))
{
    $stripped_result = ltrim(strip_tags($output[1]));
    $refined_output = str_replace('  ','',$stripped_result); 
    $regex = preg_replace('[\n\n]', "\n", $refined_output);  exit();
}

这是我的输出顺序:

 Requirements
  Minimum 2 years of web development experience is required
  Experience with PHP, MySQL, HTML, CSS, and JavaScript are preferred
  Bachelors Degree in Computer Science or related field
  Full knowledge and experience of software development lifecycle
  Strong organisational and analytical skills
  Ability to work under pressure to meet deadlines and required quality standards
  Ability to multi-task and prioritize responsibilities
  Excellent oral and written communication skills

这里我想删除所有起始空格。 我需要得到这样的输出:

  Requirements
  Minimum 2 years of web development experience is required
  Experience with PHP, MySQL, HTML, CSS, and JavaScript are preferred
  Bachelors Degree in Computer Science or related field
  Full knowledge and experience of software development lifecycle
  Strong organisational and analytical skills
  Ability to work under pressure to meet deadlines and required quality standards
  Ability to multi-task and prioritize responsibilities
  Excellent oral and written communication skills

请提出一个好的解决方案

谢谢

1 个答案:

答案 0 :(得分:2)

  

我想删除所有起始空格,我需要忽略所有空格和空行。

只需用空字符串替换

^\s+

这是online demo

  • ^匹配行/字符串的开头
  • \s匹配任何空格字符[\r\n\t\f ]

示例代码:

$re = "/^\\s+/m";
$result = preg_replace($re, '', $str);