【问题标题】:Removing white space from the beginning using regular expression in PHP在 PHP 中使用正则表达式从头开始删除空格
【发布时间】:2014-08-18 12:28:46
【问题描述】:

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

请帮我解决这个问题。

这是我的代码:

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

请提出一个好的解决方案

谢谢

【问题讨论】:

  • ltrim() 可能会更好。 ;)
  • 如果你想删除所有开始的空格然后使用这个正则表达式preg_replace('^ *', "", $string);
  • 使用 trim 会删除开头和结尾的空格和特殊字符。

标签: php regex


【解决方案1】:

我想删除所有开始的空白,我需要忽略所有的空白和空行。

只用空字符串替换

^\s+

这里是online demo

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

示例代码:

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

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 2018-06-11
    • 1970-01-01
    • 2020-09-03
    • 2014-06-04
    • 2020-10-27
    • 1970-01-01
    • 2011-11-01
    • 2012-11-15
    相关资源
    最近更新 更多