Regular Expressions find and replace - php

I am having problems with RegEx in PHP and can't seem to find the answer.
I have a string, which is 3 letters, all caps ie COS.
the letters will change but always be 3 chars long and in caps, it will also be in the center of another string, surrounded by commas.
I need a regEx to find 3 caps letter inside a string and cahnge them from COS to 'COS'
(im doing this to amend a sql insert string)
I can't seem to find the regEx unless i use spercifit letter but the letters will change.
I need something along the lines of
[A-z]{3} then replace with '[A-Z]' (I know this isnt anywere near correct, just shorthand)
Anyone any suggestions?
Cheers
EDIT:
Just wanted to add incase anyone comes accross this question at a later date:
the sql insert string (provided from an external source and ftp's to my server daily)
contained the 3 capital string twice, once with commas and once with out
so I had to also remove the double commas added from the first regEx
$sqlString = preg_replace('/([A-Z]{3})/', "'$1'", $isqlString);
$sqlString = preg_replace('/\'\'([A-Z]{3})\'\'/', "'$1'", $sqlStringt);
Thanks everyone

You were actually very close. You could use:
echo preg_replace('/([A-Z]{3})/', "'$1'", 'COS'); //will output 'COS'
For MySQL statements I would advise to use the function mysql_real_escape_string() though.

$string = preg_replace('/([A-Z]{3})/', "'$1'", $string);
http://php.net/manual/en/function.preg-replace.php

Assuming it's like you said, "three capital letters surrounded by commas, e.g.
Foo bar,COS,Foo Bar
You can use look-ahead and look-behinds and find the letters:
(?<=,)([A-Z]{3})(?=,)
Then a simple replace to surround with single quotes will be adequate:
'$1'
All together, Here's it working.

preg_replace('/(^|\b)([A-Z]{3})(\b|$)/', "'${2}'", $string);

Related

regular expression gone wrong

I want to find all strings looking like [!plugin=tesplugin arg=dfd arg=2!] and put them in array.
Important feature: the string could contain arg=uments or NOT(in some cases). and of course there could be any number of arg's. So the string could look like:
[!plugin=myname!] or [!plugin=whatever1 arg=22!] or even [!plugin=gal-one arg=1 arg=text arg=tx99!]. I need to put them all in $strarray items
Here is what i did...
$inp = "[!plugin=tesplugin arg=dfd!] sometxt [!plugin=second arg=1 arg=2!] 1sd";
preg_match_all('/\[!plugin=[a-z0-9 -_=]*!]/i', $inp, $str);
but $str[0][0] contains:
[!plugin=tesplugin arg=dfd!] sometxt [!plugin=second arg=1 arg=2!]
instead of putting each expression in a new array item..
I think my problem in regex.. but can't find one. Plz help...
The last ] needs to be escaped and the - in the character class needs to be at the start, end, or escaped. As is it is a range of ascii characters between a space and underscore.
\[!plugin=[a-z0-9 \-_=]*!\]
Regex101 Demo: https://regex101.com/r/zV4bO2/1

preg_replace add links around words starting with some-part-of-a-word

I've got this preg_replace in php which almost correctly replaces every word starting with 'exploit' into links:
preg_replace('#[\b]?(exploit([^ ]*))[\b]?#', '<a>$1</a>', 'My exploits are exploitable.');
I get this:
My <a>exploits</a> are <a>exploitable.</a>
Which is half wrong, the fullstop should not be linked on the second word. I know I need to replace the above part [^ ] to something like [^\b] but it doesn't work.
I know I can always do i.e [^ .] but it would only work on words ending with space and fullstops, not commas for example.
\b(exploit[a-zA-Z]*) should do the trick.
Aside: This website is pretty handy for trying out preg_replace: http://www.fullonrobotchubby.co.uk/random/preg_tester/preg_tester.php
\bexploit(\w*)\b - more simple....
have fun
regexrDemo
EDIT
as commented if you want only letters:
/\bexploit([a-z]*)\b/i
regexrDemo only letters
If you want to deal with unicode, you could do:
preg_replace('#\b(exploit\pL*)#u', '<a>$1</a>', 'My exploits are exploitable.');
Where \pL stands for any letter.

PHP Regex: match text urls until space or end of string

This is the text sample:
$text = "asd dasjfd fdsfsd http://11111.com/asdasd/?s=423%423%2F gfsdf http://22222.com/asdasd/?s=423%423%2F
asdfggasd http://3333333.com/asdasd/?s=423%423%2F";
This is my regex pattern:
preg_match_all( "#http:\/\/(.*?)[\s|\n]#is", $text, $m );
That match the first two urls, but how do I match the last one? I tried adding [\s|\n|$] but that will also only match the first two urls.
Don't try to match \n (there's no line break after all!) and instead use $ (which will match to the end of the string).
Edit:
I'd love to hear why my initial idea doesn't work, so in case you know it, let me know. I'd guess because [] tries to match one character, while end of line isn't one? :)
This one will work:
preg_match_all('#http://(\S+)#is', $text, $m);
Note that you don't have to escape the / due to them not being the delimiting character, but you'd have to escape the \ as you're using double quotes (so the string is parsed). Instead I used single quotes for this.
I'm not familar with PHP, so I don't have the exact syntax, but maybe this will give you something to try. the [] means a character class so |$ will literally look for a $. I think what you'll need is another look ahead so something like this:
#http:\/\/(.*)(?=(\s|$))
I apologize if this is way off, but maybe it will give you another angle to try.
See What is the best regular expression to check if a string is a valid URL?
It has some very long regular expressions that will match all urls.

Preg_match when string is sometimes a single word?

I'm trying to pull a word out of an email subject line to use as a category for attached email. Preg_match works great as long as it's not just a single word (which is what I'd like to do anyway). If there is only one word in the subject line, I just get an empty array. I've tried to treat $matches as just a variable in that case, but that doesn't work either. Can anyone tell me if preg_match will work on a single word, or what the better way to do this would be?
Thanks very much
Assuming \b(?:word1|word2|word3)\b
The reason it wont match "word1" is because you included a word separator, the \b.
What you can do is just simply always inject the word separator:
preg_match("\b(?:word1|word2|word3)\b", "." . $subject . ".", $matches);
Crude but effective.
preg_match will work on a string one character long. I think that the issue here is probably your regex. My guess is that you're testing for whitespace and because it isn't finding any it says that there is no match. Try appending '^([^\s]*)$|' to your regex and I wager it will start picking up those one word values. ([^\s] means give me anything which has no spaces in it, | means 'or'. By adding it to the front of your regex, it will include things without whitespace or whatever you already had)

Replacing a string inside a string in PHP

I have strings in my application that users can send via a form, and they can optionally replace words in that string with replacements that they also specify. For example if one of my users entered this string:
I am a user string and I need to be parsed.
And chose to replace and with foo the resulting string should be:
I am a user string foo I need to be parsed.
I need to somehow find the starting position of what they want to replace, replace it with the word they want and then tie it all together.
Could anyone write this up or at least provide an algorithm? My PHP skills aren't really up to the task :(
Thanks. :)
$result = preg_replace('/\band\b/i', 'foo', $subject);
will find all occurences of and where it's a word on its own and replace it with foo. \b ensures that there is a word boundary before and after and.
use preg_replace. You don't need to think so hard about this though you will have to learn a little bit about regexes. :)
Read up on str_replace, or for more complex replacements on Regular Expressions and preg_replace.
Examples for both:
<?php
$str = 'I am a user string and I need to be parsed.';
echo str_replace( 'and', 'foo', $str ) . "\n";
echo preg_replace( '/and/', 'foo', $str ) . "\n";
?>
In response to the comments of this answer, note that both examples above will replace every occurrence of the search string (and), even when it happens to be within another word.
To take care of that you either have to add the word separators to the str_replace call (see the comment of an example), but this will get quite complicated when you want to take care of all common word separators (space, commas, dots, exclamation marks, question marks etc.).
An easier to way to fix this problem is to use the power of regular expressions and make sure, the actual search string is not found within another word. See Tim Pietzcker's example below for a possible solution.

Categories