0

剧本:

<?php
    $dir = 'http://www.example.com/';
    $page = '
        <script src="folder/script.js" type="text/javascript"></script>
        <script type="text/javascript" src="folder/script.js"></script>';
    $last = $data = $property = 0;
    //search for all script tags
    while (($last = stripos($page, '<script', $property))!==false) {
        //find src property
        $property = stripos($page, 'scr', $last);
        if ($property===false && $property > $last+50) continue;
        //find the start of the address
        $data = stripos($page, '"', $property) + 1;
        if ($data===false && $data > $prop+5) continue;
        if (substr($page, $data, 4) !== 'http') {
            $page = substr($page, 0, $data) . $dir . substr($page, $data);
        }
    }
    echo $page;
?>

输出:

<script src="http://www.example.com/folder/script.js" type="text/javascript"></script>
<script type="http://www.example.com/text/javascript" src="folder/script.js"></script>

为什么在第一个 (") 之后插入 $dir,而不是在 src 属性的 (") 之后?

4

1 回答 1

1

使用正则表达式:

$dir = 'http://www.example.com/';
$page = '
    <script src="folder/script.js" type="text/javascript"></script>
    <script type="text/javascript" src="folder/script.js"></script>';
$regex = '#(<script .*src=")#';
$replace = '\1\2' . $dir;
$page = preg_replace($regex, $replace, $page);
echo htmlspecialchars($page);

结果:

<script src="http://www.example.com/folder/script.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.example.com/folder/script.js"></script>
于 2013-10-02T19:15:24.753 回答