I need to match links, but only those who don’t begin with the string [image:x] where x is the link itself.
I need this in a preg_replace so that only links that fit will be changed, here is an example:
“a dog once ate my book
http://mysite.com/dog.jpgand I had to go to
the storehttps://www.mysite.com/images/store.pngand buy a new iPad
apple.com/iPad/iPadMini.jpgAnd there it was fun
[image:http://apple.com/iPad/images/iPads.com]”
would result as
“a dog once ate my book
[image:http://mysite.com/dog.jpg]and I had to go to
the store[image:https://www.mysite.com/images/store.png]and buy a new iPad
[image:apple.com/iPad/iPadMini.jpg]And there it was fun
[image:http://apple.com/iPad/images/iPads.com]”
Notice the last link, as for now I get it doubled (the link is still picked up by preg_replace). like here (not the desired effect, I need it untouched):
...[image:apple.com/iPad/iPadMini.jpg]And there it was fun
[image:[image:http://apple.com/iPad/images/iPads.com]]“
Here’s my preg_replace as for now:
preg_replace('~(https?://)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\S*)\.(jpg|png|jpeg|bmp|gif)~','[[image:$0]]',$text);
You can use a negative lookbehind.
We don’t want it to start with ‘[image:’. We also don’t want to start in the middle of a word. this is prevented using
\b. If the string starts withhttp://it should be included in the match, so don’t match afterhttp://orhttps://.Check this PHP fiddle
Note: that also won’t replace a string with the final
]missing, like[image:example.com.