dsasd12314 2018-08-11 11:17
浏览 61
已采纳

preg_match - 结束标记和开始标记之间的文本

I've very odd task to do.

I need to grab text from html tags using preg_match() function in PHP. Problem is that text I need is between closing and opening html tags or this text with tags.

Below is my html string:

<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong>&nbsp; 

To be more specific: I need string " 1 category " between </h2> and <strong> tag.

When i try to grab text between opening and closing tags - It's working fine and I'm using this function:

preg_match_all('#<strong>(.*?)</strong>#',$string,$matches);

I've tried many combinations to get text between closing and opening tags. None of them worked out. I've ended using function like this:

preg_match_all('#<\/strong>(.*?)<strong>#',$content,$matches_all);

With no results.

The strange thins is that on online regex testers this function with above pattern with above function works sometimes.

Do I have bad pattern? Am I missing some flags? Do you know what can be best way to get text in this way? Unfortunately I have to do with Regex approach, the solutions like XMLDomParser is not allowed in my case.

Thanks a lot for help.

  • 写回答

3条回答 默认 最新

  • dongzhui2636 2018-08-11 12:30
    关注

    Looks like something wrong with your php installation/configuration.

    Your code as it's.

    $content = '<h2>Title of post</h2> 1 category <strong>task 1</strong> 1 category <strong>task 2</strong> 1 category <strong>task 3</strong>&nbsp;'; 
    preg_match_all('#<\/h2>(.*?)<strong>#',$content,$matches);
    print_r($matches);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => </h2> 1 category <strong>
            )
    
        [1] => Array
            (
                [0] =>  1 category 
            )
    
    )
    

    Live demo

    Note: Since there is only one match of your pattern ( between </h2> <strong>) you can access like $maches[1][0] or use preg_match.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器