【问题标题】:Issue with Str_ReplaceStr_Replace 的问题
【发布时间】:2012-12-10 14:02:04
【问题描述】:

我是一个初学者程序员,制作一个相当简单的抓取网站并将信息私下存储在 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 之后和之前保持不变。怎么会?

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

【问题讨论】:

    标签: php regex str-replace


    【解决方案1】:

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

    How to parse HTML

    Regex 可以在这种特定情况下使用,但由于这是一个学习项目,因此您希望正确地进行操作。

    【讨论】:

      【解决方案2】:

      您想使用preg_replace(),但是您不应该真正使用正则表达式来操作HTML。请改用 PHP 的 DOMDocument

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-08
        • 2020-03-12
        • 1970-01-01
        相关资源
        最近更新 更多