0

i want to change : to _ like

<img src="http://domainname.com/image:name.jpg">

output

<img src="http://domainname.com/image_name.jpg">

I have this regex but it doesn't work:

$f1content = preg_replace('/\<img src="\/\/(.*\.jpg"|.jpeg"|.gif" |.png"|.jpg">|.jpeg">|.gif">|.png">)/','/1',$content)

$result = str_replace(':', '_', $f1content);
3
  • : is not regex, /\:/ is regex Commented Feb 16, 2017 at 1:10
  • the second line with str_replace should be all that you need... Commented Feb 16, 2017 at 1:36
  • edit, update, how to replace image name only Commented Feb 16, 2017 at 2:45

1 Answer 1

3

If you just want to change from image:name.jpg to image_name.jpg you can use something like:

<?php
    $name = "image:name.jpg";

    $name = preg_replace('/\:/','_',$name);

    echo $name;

This will echo image_name.jpg

You can also use str_replace which should be faster then preg_replace, according to this entry. Which would be something like:

<?php
        $name = "image:name.jpg";

        $name = str_replace(':','_',$name);

        echo $name;

And this will also echo image_name.jpg

If you want to replace the whole URL maintaining the : in http://.... you can use \K.

According to Maroun Maroun:

\K tells the engine to pretend that the match attempt started at this position.

With the following code:

<?php
    $name = '<img src="http://domainname.com/image:name.jpg">';

    $name = preg_replace('/[^http:]\K(:)/', '_', $name);

    echo $name;

It will echo <img src="http://domainname.com/image_name.jpg">. You can see a working example here.

Sign up to request clarification or add additional context in comments.

1 Comment

how to change name only, without others name,, if i use this, output = http_domain.com/image_name.jpg

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.