0

The script:

<?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;
?>

output:

<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>

Why is it inserting $dir after the first ("), not after the (") of src attribute?

8
  • 2
    You have a typo in there: scr instead of src in $property = stripos($page, 'scr', $last); .. Just sayin' Commented Oct 2, 2013 at 18:53
  • $last = $data = $property = 0; <= can you do that? Commented Oct 2, 2013 at 18:56
  • @Fred-ii- yes, why not? I suggest you read the manual... Commented Oct 2, 2013 at 18:57
  • @OIS I will, thanks. Like Ansel Adams was a photographic genius/master, thought of himself as a "student" of the "art" ;-) cheers Commented Oct 2, 2013 at 18:58
  • 1
    if ($property===false && $property > $last+50) continue; <- This will never be true. It can be reduced to: if (0 > 50) Commented Oct 2, 2013 at 19:03

1 Answer 1

1

Using regex:

$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);

Result:

<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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.