简体   繁体   English

PHP正则表达式不起作用

[英]php regex doesn't work

this is my string 这是我的弦

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';

this is my regex 这是我的正则表达式

/<ul[^>]*>.*?<\/ul>/g

this is my code 这是我的代码

$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', 'bar', $var);

i want to replace all ul elements to bar so after this code my string should look like this 我想将所有ul元素替换为bar,因此在此代码后,我的字符串应如下所示

foo barfoo bar barfoo

It works in regex101.com perfectly, but doesn't replace anyting in php Any ideas what's wrong with my code or regex? 它可以在regex101.com上完美运行,但不能代替php中的任何内容。任何想法我的代码或regex有什么问题?

//edit //编辑
After answers, I tried this and worked then I realized my original string had newlines in it. 回答之后,我尝试了一下并工作了,然后我意识到原来的字符串中包含换行符。 So I changed my regex to this and it works now 所以我将正则表达式更改为此,现在可以正常工作

/<ul[^>]*>(.|\r|\n)*?<\/ul>/g

Thanks for your answers :) 感谢您的回答:)

Well, I had those code tested and it turned out OK: 好吧,我对那些代码进行了测试,结果确定:

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';
$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', 'bar', $var);
echo $var;

please try it. 请尝试一下。

To get the result as you mentioned in your question foo barfoo bar barfoo try following 要获得您在问题中提到的结果foo barfoo bar barfoo尝试以下操作

<?php

$var = 'foo<ul class="foo"> test </ul>foo<ul class="bar">foo</ul><ul></ul>foo';
$var = preg_replace('/<ul[^>]*>.*?<\/ul>/', ' bar', $var);
echo $var;

?>

I added a space in replace string ' bar' 我在替换字符串“ bar”中添加了一个空格

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM