代码之家  ›  专栏  ›  技术社区  ›  Ali

用于解析字符串的PHP Regex帮助

  •  3
  • Ali  · 技术社区  · 14 年前

    我有如下字符串:

    Are you looking for a quality real estate company? 
    
    <s>Josh's real estate firm specializes in helping people find homes from          
    [city][State].</s>
    
    <s>Josh's real estate company is a boutique real estate firm serving clients 
    locally.</s> 
    
    In [city][state] I am sure you know how difficult it is
    to find a great home, but we work closely with you to give you exactly 
    what you need
    

    我想把这一段分成一个数组的基础上 <s> </s> 标记,因此我有以下数组作为结果:

    [0] Are you looking for a quality real estate company?
    [1] Josh's real estate firm 
        specializes in helping people find homes from [city][State].
    [2] Josh's real estate company is a boutique real estate firm serving clients 
        locally.
    [3] In [city][state] I am sure you know how difficult it is
        to find a great home, but we work closely with you to give you exactly 
        what you need
    

    这是我当前使用的正则表达式:

    $matches = array();
    preg_match_all(":<s>(.*?)</s>:is", $string, $matches);
    $result = $matches[1];
    print_r($result);
    

    但是这个只返回一个数组,其中包含在 <s></s>

    2 回复  |  直到 14 年前
        1
  •  2
  •   BoltClock    14 年前

    我能找到的最接近的就是 preg_split() 取而代之的是:

    $string = <<< STR
    Are you looking for a quality real estate company? <s>Josh's real estate firm 
    specializes in helping people find homes from [city][State].</s>
    <s>Josh's real estate company is a boutique real estate firm serving clients 
    locally.</s> In [city][state] I am sure you know how difficult it is
    to find a great home, but we work closely with you to give you exactly 
    what you need
    STR;
    
    print_r(preg_split(':</?s>:is', $string));
    

    得到这个结果:

    Array
    (
        [0] => Are you looking for a quality real estate company? 
        [1] => Josh's real estate firm 
    specializes in helping people find homes from [city][State].
        [2] => 
    
        [3] => Josh's real estate company is a boutique real estate firm serving clients 
    locally.
        [4] =>  In [city][state] I am sure you know how difficult it is
    to find a great home, but we work closely with you to give you exactly 
    what you need
    )
    

    除了生成一个额外的数组元素(索引 2 [city][State].</s> <s>Josh's real estate company .

    不过,添加一些代码来删除空白匹配项是很简单的,但我不确定您是否希望这样做。

        2
  •  1
  •   Codler    14 年前

    我建议你调查一下多姆 http://php.net/manual/en/book.dom.php