Why does this PHP regex give me error? - php

Need Some Help With Regex:
I want to replace
[url=http://youtube.com]YouTube.com[/url]
with
YouTube.com
the regex
preg_replace("/[url=(.*?)](.*?)[/url]/is", '$2', $text);
why does this give me:
Warning: preg_replace() [function.preg-replace]: Unknown modifier 'r' in C:\Programa\wamp\www\func.php on line 18

You should escape special characters in your regular expression:
preg_replace('/\[url=(.*?)](.*?)\[\/url]/is', '$2', $text);
I have escaped the [ characters (they specify the start of a character class) and the / character (it specifies the boundaries of the regular expression.)
Alternatively (for the / character) you can use another boundary character:
preg_replace('#\[url=(.*?)](.*?)\[/url]#is', '$2', $text);
You still have to escape the [ characters, though.

PHP is interpreting the '/' in /url as being the end of the regex and the start of the regex options. Insert a '\' before it to make it a literal '/'.
You need to escape the '['s in the same way (otherwise they will be interpreted as introducing a character class).
preg_replace("/\[url=(.*?)](.*?)\[\/url]/is", '$2', $text);

Both the slashes and square brackets are special characters in regex, you will need to escape them:
\/ \[ \]

The 2nd '/' in a regex string ends the regex. You need to escape it. Also, preg_replace will interpret the '[url=(.*?)]' as a character class, so you need to escape those as well.
preg_replace('/\[url=(.*?)\](.*?)\[\/url\]/is', '$2', $text);

You seem to be just starting out with regular expressions. If that is the case - or maybe even if it isn't - you will find the Regex Coach to be a very helpful tool. It provides a sandbox for us to test our pattern matches and our replace strings too. If you had been using that it would have highlighted the need to escape the special characters.

Related

Regex escape escape characters in PHP

So I have this regex that works on regex101.com
(?:[^\#\\S\\+]*)
It matches the first from first#second.
Whenever I try to use my regex with PHP's preg_replace I don't get the result I expect.
So far I tried it via preg_quote():
\(\?\:\[\^\\#\\S\\\+\]\*\)
And tried it with escaping the original \\ with 4 \'s:
\(\?\:\[\^\\#\\\\S\\\\\+\]\*\)
Still no success. Am I doing something fundamentaly wrong?
I'm just using:
preg_replace("/$regex/", "", $string);
All my other regexes that don't need so many escape chars work perfectly that way.
When you use (?:[^\#\\S\\+]*) in a preg_match in PHP, both in a single or double quoted string literal, the \\S is parsed as a non-whitespace pattern. [^\S] is equal to \s, i.e. it matches whitespace.
The preg_quote() function is only meant to be used to make any string a literal one for a regex, it just escapes all chars that are sepcial regex metacharacters / operators (like (, ), [, etc.), thus you should not use it here.
While you could use a regex to match 1+ chars other than whitespace and # from the start of a string like preg_match('~^[^#\s]+~', $s, $match), you can just explode your input string with # and get the 0th item.

Explode and/or regex text to HTML link in PHP

I have a database of texts that contains this kind of syntax in the middle of English sentences that I need to turn into HTML links using PHP
"text1(text1)":http://www.example.com/mypage
Notes:
text1 is always identical to the text in parenthesis
The whole string always have the quotation marks, parenthesis, colon, so the syntax is the same for each.
Sometimes there is a space at the end of the string, but other times there is a question mark or comma or other punctuation mark.
I need to turn these into basic links, like
text1
How do I do this? Do I need explode or regex or both?
"(.*?)\(\1\)":(.*\/[a-zA-Z0-9]+)(?=\?|\,|\.|$)
You can use this.
See Demo.
http://regex101.com/r/zF6xM2/2
You can use this replacement:
$pattern = '~"([^("]+)\(\1\)":(http://\S+)(?=[\s\pP]|\z)~';
$replacement = '\1';
$result = preg_replace($pattern, $replacement, $text);
pattern details:
([^("]+) this part will capture text1 in the group 1. The advantage of using a negated character class (that excludes the double quote and the opening parenthesis) is multiple:
it allows to use a greedy quantifier, that is faster
since the class excludes the opening parenthesis and is immediatly followed by a parenthesis in the pattern, if in an other part of the text there is content between double quotes but without parenthesis inside, the regex engine will not go backward to test other possibilities, it will skip this substring without backtracking. (This is because the PCRE regex engine converts automatically [^a]+a into [^a]++a before processing the string)
\S+ means all that is not a whitespace one or more times
(?=[\s\pP]|\z) is a lookahead assertion that checks that the url is followed by a whitespace, a punctuation character (\pP) or the end of the string.
You can use this regex:
"(.*?)\(.*?:(.*)
Working demo
An appropriate Regular Expression could be:
$str = '"text1(text1)":http://www.example.com/mypage';
preg_match('#^"([^\(]+)' .
'\(([^\)]+)\)[^"]*":(.+)#', $str, $m);
print ''.$m[2].'' . PHP_EOL;

preg_replace - regular expression php for two different characters

Is this a correct syntax for preg_replace (regular expression) to remove ?ajax=true or &ajax=true from a string?
echo preg_replace('/(\?|&)ajax=true/', '', $string);
So for example /hello/hi?ajax=true will give me /hello/hi and /hello/hi?ajax=true will give me /hello/hi
Do I need to escape &?
Why don't you try it?
You don't need to escape "&". It is not a special character in regex.
Your expression should be working, that is an alternation that you are using. But if you have only single characters in your alternation, it is more readable, if you use a character class.
echo preg_replace('/[?&]ajax=true/', '', $string);
[?&] is a character class, it will match one character out of the characters listed between the square brackets.
I think it is ok your expression. You can add (?i) to ignore Upper Case letters. The result should be something like:
echo preg_replace('/(\?|&)(?i)ajax=true/', '', $string);

PHP : couldn't replace using preg_replace()

Just I'm replacing the object tag in the given string
$matches = preg_replace("/<object(.+?)</object>/","replacing string",$str);
but it is showing the error as
Warning: preg_replace() [function.preg-replace]: Unknown modifier 'o'
What went wrong?
The slash in </object> has to be quoted: <\/object>, or else it is interpreted as the end of your regex since you're delimiting it with slashes. The whole line should read:
$matches = preg_replace("/<object(.+?)<\\/object>/","replacing string",$str);
In your regex the forward slash is the regex delimiter. As you are dealing with tags, better use another delimiter (instead of escaping it with a backslash):
$matches = preg_replace("#<object(.+?)</object>#", "replacing string", $str);
There are other delimiteres, too. You can use any non-alphanumeric, non-backslash, non-whitespace character. However, certain delimiters should not be used under any circumstances: |, +, * and parentheses/brackets for example as they are often used in the regular expressions and would just confuse people and make them hate you.
Btw, using regular expressions for HTML is a Bad Thing!
The first character is taken as delimiter char to separate the expression from the flags. Thus this:
"/[a-z]+/i"
... is internally split into this:
- Pattern: [a-z]+
- Flags: i
So this:
"/<object(.+?)</object>/"
... is not a valid regexp. Try this:
"#<object(.+?)</object>#"

php regex is not escaped

what is a regex to find any text that has 'abc' but does not have a '\' before it. so it should match 'jfdgabc' but not 'asd\abc'. basically so its not escaped.
Use:
(?<!\\)abc
This is a negative lookbehind. Basically this is saying: find me the string "abc" that is not preceded by a backslash.
The one problem with this is that if you want to allow escaping of backslashes. For example:
123\\abcdef
(ie the backslash is escaped) then it gets a little trickier.
$str = 'jfdg\abc';
var_dump(preg_match('#(?<!\\\)abc#', $str));
Try the regex:
(?<!\\)abc
It matches a abc only if its not preceded by a \

Categories