Str_Replace存在问题

3

我是一个初学者程序员,正在制作一个相当简单的网页爬取和将信息私下存储到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;

理论上,应该删除到部分的所有内容。我哪里错了?在str_replace之前和之后,文本保持不变。为什么?
谢谢任何和所有帮助!如果需要更多细节,我很乐意提供!
2个回答

2

2
不要使用正则表达式解析HTML。
请参考如何解析HTML
在这种特定情况下,正则表达式可以起作用,但由于这是一个学习项目,您需要做得正确。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接