【问题标题】:php - change value to src attribute if 'cid:' are found in html documentphp - 如果在 html 文档中找到“cid:”,则将值更改为 src 属性
【发布时间】:2015-05-30 00:27:01
【问题描述】:

如何告诉 php 查看 src 属性是否以 'cid:' 开头,如果是,则将其替换为另一个值?

<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">

<?php
    $new_link = "http://www.example.com'";
    preg_replace("#^cid:#", $new_link);
?>

【问题讨论】:

  • 更换的时候,你知道xxxx...是什么吗?如果你知道那个 xxxx.. 是什么,你可以构建那个 cid:xxxxxxx... 字符串,然后使用 str_replace 用链接替换它。正则表达式很乱
  • NO 结果总是不同的。
  • cid 链接是通过 html 生成的,因此脚本需要查看 html,如果找到 src="cid:' 则用新字符串替换它们。codepad.viper-7.com/uNaUvZ

标签: php html preg-replace preg-match-all src


【解决方案1】:

^ 用于字符串或行的开头,具体取决于所使用的修饰符。你想要的

<?php
$new_link = "http://www.example.com'";
echo preg_replace('~src="cid.*?"~',"src='$new_link'", '<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">');
?>

输出:

<img src='http://www.example.com'' width="544" height="340">

src 末尾的第二个尾随单引号来自$newlink。

. 表示任意字符 * 表示任意数量的“任意字符”,? 表示在第一次出现下一个字符时停止。在这种情况下,这是一个双引号,应该使它捕获整个字符串 src 属性。

如果 src 可以同时使用单引号或双引号,这应该说明这一点(另请注意,我在此处从 $newlink 中删除了尾随引号)。

<?php
$new_link = "http://www.example.com";
echo preg_replace('~src=("|\')cid.*?\1~',"src='$new_link'", '<img src="cid:xx_xxxxxxxx_xxxxxxxxxxxxxxxxxxx" width="544" height="340">');
?>

【讨论】:

  • 谢谢,但使用“#src="cid.*?"#" 会停止工作。应该是这个吗? "#src=cid"."*?#"
  • 编辑后你试过了吗?一开始我把引号弄错了。
  • 好的。如果 '' 生成但并不总是相同怎么办?
  • 只要一直是src="cid:anythinghere"就可以了。
猜你喜欢
  • 2019-11-14
  • 2022-01-26
  • 2017-02-20
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 1970-01-01
  • 2019-03-13
  • 2013-06-14
相关资源
最近更新 更多