0

我正在尝试用 div 中的 PHP 替换文本,

西大街 18 号

虽然如果文本是19 West Main Street. 如果是这样,它会被改变成别的东西。我试过用一个数组来做这个,但没有运气。

http://php.net/manual/en/function.array-replace.php,尽管我找不到使用 if 语句并包括 div 标签中更改的文本的方法。

4

2 回答 2

4

像下面这样的东西应该让你开始:

<?php
$html = '<div>19 West Main Street</div><div>18 West Main Street</div>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xPath = new DOMXPath($doc);
$nodes = $xPath->query("//div[text() = '18 West Main Street']|//div[text() = '19 West Main Street']");

foreach ($nodes as $node) {
    if ($node->nodeValue == '18 West Main Street') {
        $node->nodeValue = 'Something';
    } else {
        $node->nodeValue = 'something else';
    }
}

echo $doc->saveHTML();

演示:http ://codepad.viper-7.com/V4ZMPT

它找到所有div带有文本的 s 并将其19 / 18 West Main Street替换为“something (else)”。如果那不是您想要的,我不完全理解您的问题:)

或者,如果您只想替换文本19 West Main Street,您可以这样做:

<?php
$html = '<div>19 West Main Street</div>';

$doc = new DOMDocument();
$doc->loadHTML($html);

$xPath = new DOMXPath($doc);
$nodes = $xPath->query("//div[text() = '19 West Main Street']");

foreach ($nodes as $node) {
    $node->nodeValue = 'something else';
}

echo $doc->saveHTML();

演示:http ://codepad.viper-7.com/HeLk5i

于 2012-12-26T04:24:23.360 回答
0

我已经这样做了,而且效果很好:)

下面的链接显示了工作示例 { http://jsfiddle.net/SagarPPanchal/u225F/1/ } 谢谢

正是我不知道如何在这里以正确的方式编写链接,所以我很抱歉

<div id="example2div" style="border-style:solid; padding:20px;">Replace me with something, please.</div>
    <textarea cols="36" rows="4" name="new" style="width:350px;" onchange="EffectReplacement(this)" wrap="on"></textarea>
    <select onchange="" id="s_box" style="visibility: hidden;">
        <option value="TEST_ONE">TEST_ONE</option>
        <option value="TEST_TWO">TEST_TWO</option>
    </select>
    <br />
    <input type="button" value="Change Content" style="width:350px;" onclick="return show_stuff();">
    <br />
    <input type="button" value="Hide Content" style="width:350px;" onclick="return hide_stuff();">



<script>
 function ReplaceContentInContainer(id, content) {
     var container = document.getElementById(id);
     container.innerHTML = content;
 }

 function EffectReplacement(it) {
     re = /script/ig;
     var content = it.value.replace(re, 's.c.r.i.p.t');
     ReplaceContentInContainer('example2div', content);
 }

 function show_stuff() {
     document.getElementById('s_box').style.visibility = "Visible";
 }

 function hide_stuff() {
     document.getElementById('s_box').style.visibility = "hidden";
 }
</script>
于 2013-04-26T12:30:49.597 回答