PHP替换src链接并保留url

时间:2017-01-06 15:23:33

标签: php regex preg-replace

我有这样的源代码:

<script type='text/javascript' src='http://html.com/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=4.6'></script>
<script type='text/javascript'></script>
<script type='text/javascript' src='http://html.com/wp-content/plugins/table-of-contents-plus/front.min.js?ver=1509'></script>
<script type='text/javascript' src='http://html.com/wp-includes/js/wp-embed.min.js?ver=4.7'></script>

如何将所有src属性替换为:

http://www.example.com/site=PLACEHOLDER&somethingelse”? 所以我需要用{src网站从上面}替换PLACEHOLDER

我找到了代码片段,我可以替换src链接但不用替换的url替换它。

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

假设您在变量中包含源代码,您可以这样做:

$code = "
<script type='text/javascript' src='http://html.com/wp-content/plugins/contact-form-7/includes/js/scripts.js?ver=4.6'></script>
<script type='text/javascript'></script>
<script type='text/javascript' src='http://html.com/wp-content/plugins/table-of-contents-plus/front.min.js?ver=1509'></script>
<script type='text/javascript' src='http://html.com/wp-includes/js/wp-embed.min.js?ver=4.7'></script>";

$pattern = "/src='([^']+)/i";
$replacement = "src='http://www.example.com/site=$1&somethingelse";

echo preg_replace($pattern, $replacement, $code);