Need to match multiple backslahes in a PHP regex - php

I'm trying to match 4 backslahes using preg_match.
preg_match('/\\\\\\\\/',$subject) works fine, but preg_match('/\\{4}/',$subject) doesn't.
Perhaps I'm using {} incorrectly. Could anyone advise?

Ok I got it: Two backslashes mean you want one backslash in your string: So for the regex it looks like this: /\{4}/ Which means you want to escape the {
What you need here is:
preg_match('/\\\\{4}/', $subject);
That looks for the regex like this: /\\{4}/ and works properly.

Regex is the wrong tool when you're looking for a literal string.
strpos($subject, str_repeat("\\",4)) !== false

Use this:
preg_match('/(?:\\\\){2}/',$subject, $m);
It matches 4 backslashes.

Related

PHP preg_replace pattern only seems to work if its wrong?

I have a string that looks like this
../Clean_Smarty_Projekt/tpl/templates_c\.
../Clean_Smarty_Projekt/tpl/templates_c\..
I want to replace ../, \. and \.. with a regulare expression.
Before, I did this like this:
$result = str_replace(array("../","\..","\."),"",$str);
And there it (pattern) has to be in this order because changing it makes the output a little buggy. So I decided to use a regular expression.
Now I came up with this pattern
$result = preg_replace('/(\.\.\/)|(\\[\.]{1,2})/',"",$str);
What actually returns only empty strings...
Reason: (\\[\.]{1,2})
In Regex101 its all ok. (Took me a couple of minutes to realize that I don't need the /g in preg_replace)
If I use this pattern in preg_replace I have to do (\\\\[\.]{1,2}) to get it to work. But that's obviously wrong because im not searching for two slashes.
Of course I know the escaping rulse (escaping slashes).
Why doesn't this match correctly ?
I suggest you to use a different php delimiter. Within the / delimiter, you need to use three \\\ or four \\\\ backslashes to match a single backslash.
$string = '../Clean_Smarty_Projekt/tpl/templates_c\.'."\n".'../Clean_Smarty_Projekt/tpl/templates_c\..';
echo preg_replace('~\.\./|\\\.{1,2}~', '', $string)
Output:
Clean_Smarty_Projekt/tpl/templates_c
Clean_Smarty_Projekt/tpl/templates_c

preg_match dose not work correctly in php

all,
I am using preg_match to filter some data, and it is strange that, it dose not work correctly. I am new to regex, and I used a php live regex website to check my regex, which works correctly. So I have no idea what is wrong here.
I would like to have preg_match to find something like "a\_b" in the $string:
$string="aaa\_bbb:ccc"
if(preg_match("/[a-zA-Z]\\_[a-zA-Z]/", $string)){
$snew = str_replace('\_', "_", $string);
}
But it is strange that even I have a $string like in this example above, the result of preg_match is 0. But when I change it to
preg_match("/\\_[a-zA-Z]/", $string)
It works fine and return 1. But of course that is not what I want. Any idea?
Thanks very much~
You don't really need the preg_match at all, from what I can see.
However the problem you're having with it is to do with escaping.
You have this: "/[a-zA-Z]\\_[a-zA-Z]/"
You've correctly identified that the backslash needs to be escaped, however, you've missed a subtle issue:
Regular expressions in PHP are strings. This means that you need to escape it as a string as well as a regular expression. In effect, this means that to correctly escape a backslash so it is matched as an actual backslash character in your pattern, you actually need to have four backslashes.
"/[a-zA-Z]\\\\_[a-zA-Z]/"
It's not pretty, but that's how it is.
Hope that helps.
use:
if(preg_match("/[a-zA-Z]\\\\_[a-zA-Z]/", $string))
instead
You don't need the preg_match altogether, instead just do a replace using this regex:
/([a-zA-Z])\\\\_([a-zA-Z])/
and then replace with $1_$2, like this:
$result = preg_replace("/([a-zA-Z])\\\\_([a-zA-Z])/", "$1_$2$, $string);

regex back-reference not working in PHP PCRE

I want to match matching tags like <tag>...</tag>. I tried the regex
~<([^>]+)>.*?</\1>~
but this fails. The expression worked when I used the exact text inside the angle brackets, i.e,
~<(tag)>.*?</tag>~
works, but even
~<(tag)>.*?</\1>~
fails.
I'm assuming that the back reference is not working here.
Can someone help me out please. Thanks
PS: I'm not using this to parse HTML. I know I shouldn't.
You didn't show your PHP code, but I surmise you have your regex in double quotes. If so then the backreference \1 actually is converted into an ASCII character ☺ before it reaches PCRE. (All \123 sequences are interpreted as C-string octal escapes there.)
It worked for me...
$str = '<a></a>';
var_dump(preg_match('~<([^>]+)>.*?</\1>~', $str)); // int(1)
CodePad.
Also, have you considered an XML parser? Otherwise it won't like a piece of HTML like this...
<a title="Is 4 > 6?"></a>
CodePad.
Apart from the fact that it's not always a good idea to try and match markup languages using regex, your regex looks OK. Maybe you're using it wrong?
if (preg_match('~<([^>]+)>.*?</\1>~', $subject, $regs)) {
$result = $regs[0];
} else {
$result = "";
}
should work.
Use single quotes in the pattern
preg_match_all('/(sens|respons)e and \1ibility/', "sense and sensibility", $matches);
print_r($matches);

Exact string replacement in php

I'm looking for a way to replace a string in php that exactly matches with the subject.
For example I got a file named 'hello-world.txt' having three lines:
'http://www.example.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
and I need to replace the 'http://www.example.com/' with 'http://www.example2.com'
$string=file_get_contents('hello-world.txt');
$string=str_replace('http://www.example.com/','http://www.example2.com',$string);
echo $string;
I will be getting a result similar to this:
'http://www.example2.com/'
'http://www.example2.com/category/'
'http://www.example2.com/tag/name/'
But What I actually need is something like this:
'http://www.example2.com/'
'http://www.example.com/category/'
'http://www.example.com/tag/name/'
Please Help!!!!
You can use preg_replace with the m modifier as:
$string=preg_replace('~^http://www\.example\.com/$~m','http://www.example2.com',$string);
Code In Action
First check if the current line is what you're looking for. If not, just spit it back out.
Either $string=str_replace("'http://www.example.com/'", "'http://www.example2.com'", $string); since in your example you have single quotes around each line or use preg_replace like this:
$string=preg_replace('/^http:\/\/www\.example\.com\/$/', 'http://www.example2.com/', $string);
... if those single quotes aren't supposed to be there. The $ at the end of the regex means the end of the line and the ^ means the beginning of the line. Periods and / need to be escaped hence the \. and \/
I haven't tested this code. Here is a link to preg_replace() http://php.net/manual/en/function.preg-replace.php

How to write regex to find one directory in a URL?

Here is the subject:
http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov
What I need using regex is only the bit before the last / (including that last / too)
The 937IPiztQG string may change; it will contain a-z A-Z 0-9 - _
Here's what I tried:
$code = strstr($url, '/http:\/\/www\.mysite\.com\/files\/get\/([A-Za-z0-9]+)./');
EDIT: I need to use regex because I don't actually know the URL. I have string like this...
a song
more text
oh and here goes some more blah blah
I need it to read that string and cut off filename part of the URLs.
You really don't need a regexp here. Here is a simple solution:
echo basename(dirname('http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov'));
// echoes "937IPiztQG"
Also, I'd like to quote Jamie Zawinski:
"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."
This seems far too simple to use regex. Use something similar to strrpos to look for the last occurrence of the '/' character, and then use substr to trim the string.
/http:\/\/www.mysite.com\/files\/get\/([^/]+)\/
How about something like this? Which should capture anything that's not a /, 1 or more times before a /.
The greediness of regexp will assure this works fine ^.*/
The strstr() function does not use a regular expression for any of its arguments it's the wrong function for regex replacement.
Are you thinking of preg_replace()?
But a function like basename() would be more appropriate.
Try this
$ok=preg_match('#mysite\.com/files/get/([^/]*)#i',$url,$m);
if($ok) $code=$m[1];
Then give a good read to these pages
http://www.php.net/preg_match
preg_replace
Note
the use of "#" as a delimiter to avoid getting trapped into escaping too many "/"
the "i" flag making match insensitive
(allowing more liberal spellings of the MySite.com domain name)
the $m array of captured results

Categories