Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
preg_替换PHP中的HTML代码_Php_Regex - Fatal编程技术网

preg_替换PHP中的HTML代码

preg_替换PHP中的HTML代码,php,regex,Php,Regex,我想从html代码中删除如下字符串 3 所以我想出了正则表达式 $pattern=“/\\w\\w?/um” 然而,正则表达式不起作用。有人能指出我做错了什么吗。我是PHP新手 当我使用一个简单的正则表达式进行测试时,它是有效的,所以问题仍然存在于正则表达式中 $str = $_POST["txtarea"]; $pattern = $_POST["regex"]; echo preg_replace($pattern, "", $str); 尽管我极力主张在这里做这项工作,但您仍

我想从html代码中删除如下字符串
3

所以我想出了正则表达式

$pattern=“/\\w\\w?/um”

然而,正则表达式不起作用。有人能指出我做错了什么吗。我是PHP新手

当我使用一个简单的正则表达式进行测试时,它是有效的,所以问题仍然存在于正则表达式中

  $str = $_POST["txtarea"];
  $pattern = $_POST["regex"];
  echo preg_replace($pattern, "", $str);

尽管我极力主张在这里做这项工作,但您仍然需要一些正则表达式,所以

px
数值的表达式可以是简单的
[\d.-]+
,因为您不想验证任何东西

span的内容可以简化为
[^。使用html解析器。下面是一个使用BeautifulSoup的python解决方案,因为我喜欢这个库来完成以下任务:

from BeautifulSoup import BeautifulSoup

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

soup = BeautifulSoup(content)
for div in soup.findAll('span', {'style':re.compile("font-size: \d(\.\d)?px; letter-spacing: -\d(\.\d)?px; color: #\w{6}")}):
    div.extract()

with open('Path/to/file.modified', 'w') as output_file:
    output_file.write(str(soup))
结束标记(结束跨距)中有一条斜线(/)


您需要转义它或使用与斜杠不同的分隔符。为什么要使用
/um
?似乎没有必要。我只是编写了一个正则表达式并生成了php正则表达式模式。不确定在php中是什么。但是删除它仍然不能解决问题。启用
错误报告
,然后用谷歌搜索结果警告。什么你想要什么的规则被删除了吗?@KennethK。基本上,里面有什么样式,比如
style="字体大小:0.8px;字母间距:-0.8px;颜色:#ecf6f6
我觉得这不像PHP。我不认为OP绝对需要PHP,他们只是选择了它。是的,我和其他人一样喜欢PHP,但beautifulsoup是一个很好的工具,你必须使用正确的工具来完成这项工作。PHP也有DOMDocument,所以我不确定你用的是哪个comment:)我只是对文档不熟悉。
from BeautifulSoup import BeautifulSoup

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

soup = BeautifulSoup(content)
for div in soup.findAll('span', {'style':re.compile("font-size: \d(\.\d)?px; letter-spacing: -\d(\.\d)?px; color: #\w{6}")}):
    div.extract()

with open('Path/to/file.modified', 'w') as output_file:
    output_file.write(str(soup))