php - Str_Replace 问题

标签 php regex str-replace

我是一名初级程序员,我制作了一个相当简单的抓取网站并将信息私下存储在 mysql 数据库中,以了解有关编程的更多信息。

这是我要抓取的代码:

<li id="liIngredient" data-ingredientid="3914" data-grams="907.2">
                <label>
                    <span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name="ctl00$CenterColumnPlaceHolder$recipeTest$recipe$ingredients$rptIngredientsCol1$ctl01$cbxIngredient" /></span>
                    <p class="fl-ing" itemprop="ingredients">
                        <span id="lblIngAmount" class="ingredient-amount">2 pounds</span>
                        <span id="lblIngName" class="ingredient-name">ground beef chuck</span>

                    </p>
                </label>
            </li>

<li id="liIngredient" data-ingredientid="5838" data-grams="454">
                <label>
                    <span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name="ctl00$CenterColumnPlaceHolder$recipeTest$recipe$ingredients$rptIngredientsCol1$ctl02$cbxIngredient" /></span>
                    <p class="fl-ing" itemprop="ingredients">
                        <span id="lblIngAmount" class="ingredient-amount">1 pound</span>
                        <span id="lblIngName" class="ingredient-name">bulk Italian sausage</span>

                    </p>
                </label>
            </li>

抓取数据后,我尝试使用 str_replace 去除除(使用第一个示例)2 磅碎牛肉(或第二个示例中的 1 磅散装意大利香肠)以外的所有内容。

这是我的尝试:

$ingredients = str_replace('#<label>\s<span class="checkbox-formatted"><input id="cbxIngredient" type="checkbox" name=".*?" /></span>\s<p class="fl-ing" itemprop="ingredients">\s#', null, $ingredients);
              echo $ingredients;

理论上,应该删除 span id=lblIngAmount 部分的所有内容。我哪里错了? str_replace 前后的文本保持不变。怎么会?

感谢所有帮助!如果您需要更多详细信息,我很乐意提供!

最佳答案

不要使用正则表达式来解析 HTML。

参见 How to parse HTML .

正则表达式适用于这种特定情况,但由于这是一个学习项目,您需要正确地进行操作。

关于php - Str_Replace 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14016415/

相关文章:

javascript - PHP 联系表单正在打开一个新的浏览器选项卡

python - 如何替换 python 正则表达式语法中的递归子模式 "(?1)"?

c# - 在精确偏移处匹配正则表达式

Javascript String.replace() ,结果不明确

java - 在java中将 "enter"变成字符串

php - fatal error : Call to undefined function mb_detect_encoding() in C:\Users\Jarek\mywebsite\phpMyAdmin\libraries\php-gettext\gettext. inc 第 177 行

php - 在 coldfusion 中反序列化 PHP 数组

php - Font Awesome 未显示 - Avada 主题 (Wordpress) - 添加 fa 类

c# - 仅接受波斯字符的正则表达式

excel - 循环遍历拆分值单元格并替换