$pattern = '/http://mysite.com/otherstuff/test.html/';
$replacement = 'http://mysite.com/otherstuff/test2.html';
echo preg_replace($pattern, $replacement, $incData);

That's my code. short and simple. seems to me that preg_replace doesn't like the slashes in my url. i get the following error

Warning: preg_replace() [function.preg-replace]: Unknown modifier '/' in ....\Apache Group\Apache\htdocs\ere.php on line 29

How can i get around this please?

thanks

    You would definitely have to escape the pattern:

    $pattern = '/http:\/\/mysite.com\/otherstuff\/test.html/';

      Two more solutions:

      Use some character other than '/' that doesn't appear in the URL to delimit your regular expression. Then you won't need to escape the '/'s that do appear in the URL.

      Don't use preg_replace. I don't see anything you're doing that can't be done by str_replace and without the added overhead.

        thanks for the replies

        I replaced the preg_replace with str_replace and it works just dandy now.

        but on an educational note, escaping the slashes in preg_replace still didnt work so i echo'd the string. the backslashes were also printed . so i could choose, an error or a string that wouldnt match. strange

          themanwhowas wrote:

          the backslashes were also printed .

          That's because you're using single quotes. PHP doesn't treat "/" as special, so it left "\/" unchanged: the backslashes would be picked up by PCRE because in that "/" did have a special meaning (it was the character you'd chosen as the pattern delimiter).

          escaping the slashes in preg_replace still didnt work

          <?php
          $incData = "This is a string with the test url http://mysite.com/otherstuff/test.html embedded within it.";
          
          $pattern = '/http:\/\/mysite.com\/otherstuff\/test.html/';
          $replacement = 'http://mysite.com/otherstuff/test2.html';
          echo preg_replace($pattern, $replacement, $incData); 
          
          

          Worked just fine for me.

          On an educational note, mysite.com is a real address. If you want a domain name to use in examples, RFC2606 reserves example.com for the purpose.

            Write a Reply...