gpt4 book ai didi

php - preg_replace 输入标签中的特定 src 属性

转载 作者:太空宇宙 更新时间:2023-11-03 16:14:02 26 4
gpt4 key购买 nike

我有一个 PayPal 按钮代码,我想为其使用我自己的图像。这是 PayPal 按钮代码:

<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> 
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="Q8LQ82SNNSBKC">
<input type="image" src="https://www.paypal.com/images/pp-buy-now-btn-bryellow.png" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>

...其中包含几个“输入”标签,我想替换输入(图像类型)的“src”。我已尽最大努力编写代码来执行此操作:

$paypal_button_code2 = preg_replace('/<input[type="image"]\ [^>]+src="([^"]+)"/', $newimageurl, $paypal_button_code);

但这行不通。

有人可以给我指明正确的方向吗(使用正确的代码,或者帮助页面以简单的方式处理正则表达式!!)

非常感谢!

最佳答案

使用 html 的方法是 DOMDocument,而不是正则表达式:

$html = '<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="Q8LQ82SNNSBKC"> <input type="image" src="https://www.paypal.com/images/pp-buy-now-btn-bryellow.png" border="0" name="submit" alt="PayPal – The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1"> </form>';

$dom = new DOMDocument;
$dom->loadHTML('<div id="root">' . $html . '</div>');
$root = $dom->getElementById('root');
$xp = new DOMXPath($dom);

$nodeList = $xp->query('//form[@action="https://www.paypal.com/cgi-bin/webscr"][1]/input[@type="image"]/@src');

if ( $nodeList ) {
$newimageurl = 'path/to/newimage.gif';
$nodeList->item(0)->nodeValue = $newimageurl;
$html = '';

foreach ($root->childNodes as $childNode) {
$html .= $dom->saveHTML($childNode);
}
}

echo $html;

XPath 查询详细信息:

//    # anywhere in the DOM tree
form # a form element
[ # open a predicate (condition on the current element)
# must have an attribute "action" with the value of this string
@action="https://www.paypal.com/cgi-bin/webscr"
]
[1] # other predicate: first occurrence of this kind of form
/ # direct child
input
[
@type="image"
]
/
@src # src attribute

关于'<div id="root">' . $html . '</div>' :

DOMDocument::loadHTML加载 html 字符串并构建 DOM 树。为此,您需要一个根元素,但由于您处理的是 html 部分而不是整个 html 文档,因此您的字符串可能未包含在唯一元素(即整个 html 文档中的 <html>...</html>)之间。为了避免来自 DOMDocument 的自动更正,技巧在于提供一个伪造的根元素。一旦 DOM 树被编辑,您所要做的就是连接根元素的所有子元素。

关于php - preg_replace 输入标签中的特定 src 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45196975/

26 4 0