php preg_split error when switching from split to preg_split - php

I get this warning from php after the change from split to preg_split for php 5.3 compatibility :
PHP Warning: preg_split(): Delimiter must not be alphanumeric or backslash
the php code is :
$statements = preg_split("\\s*;\\s*", $content);
How can I fix the regex to not use anymore \
Thanks!

The error is because you need a delimiter character around your regular expression.
$statements = preg_split("/\s*;\s*/", $content);

Although the question was tagged as answered two minutes after being asked, I'd like to add some information for the records.
Similar to the way strings are delimited by quotation marks, regular expressions in many languages, such as Perl or JavaScript, are delimited by forward slashes. This will lead to expressions looking like this:
/\s*;\s*/
This syntax also allows to specify modifiers:
/\s*;\s*/Ui
PHP's Perl-compatible regular expressions (aka preg_... functions) inherit this. However, PHP itself doesn't support this syntax so feeding preg_split() with /\s*;\s*/ would raise a parse error. Instead, you enclose it with quotes to build a regular string.
One more thing you must take into account is that PHP allows to change the delimiter. For instance, you can use this:
#\s*;\s*#Ui
What is it good for? It simplifies the use of forward slashes inside the expression since you don't need to escape them. Compare:
/^\/home\/.*$/i
#^/home/.*$#i

If you don't like delimiters, you can use T-Regx tool:
pattern("\\s*;\\s*")->split($content):
You can also use Pattern::of("\\s*;\\s*")->split()

Related

PHP refusing this regular expression

So I'm trying to check for match and if match, extract a variable name out of a string. The variable name should be preceded by "$" and cannot be escaped with "\", so for example "$name" should extract "name" and "\$name" or "name" shouldn't match. Heres the command:
$match = preg_match("/^(?<!\\)(\$.*)$/", $potential, $name);
I constructed and tested it using regex101.com and it works there, however, I'm getting an error from PHP saying
"preg_match(): Compilation failed: missing ) at offset 13 in ..."
and I have no clue what its referring to.
My thought is that you will need to escape certain characters to consume the regular expression in PHP
$match = preg_match('/^(?<!\\\\)(\$.*)$/', $potential, $name);
Edit: the backslash is the escape character in both Regex and PHP, you will need to doubly escape the slashes.
You've escaped a bracket:
preg_match('/^(?<!\\) <----HERE
FYI you can use several other delimiters to make your regex's more readable. Because so often we have slashes and escaped chars, then using '/' makes it hard to read. Consider using '#' or '~' or even '#' to increase readability.
Also reL your online regex tool of choice, it depends on which regular expression implementation (and version) the service uses, as to how accurate your results. I always use rubular.com (Uses PCRE) but for PHP you can use phpliveregex.com

regular expression error php error

I have made a regular expression to remove a script tag from a imported page.(used curl)
<script[\s\S]*?/script> this is my expresion
when i used it with preg_replace to remove the tag it gave me this error
Warning: preg_replace() [function.preg-replace]: Unknown modifier 'c' in C:\xampp\htdocs\get_page.php on line 21
can anyone help me
thanks
You should choose a suitable delimiter for your regular expression (preferably one that doesn't' occur anywhere in your pattern, so that you don't need to escape). For example:
"#<script[\s\S]*?/script>#"
Also, don't do that if you are trying to prevent malicious people from injecting Javascript into your page. It can easily be worked around. Use a whitelist of known safe constructs rather than trying to remove dangerous code.
PHP requires delimiters on RegExp patterns. Also, your expression can be simplified.
|<script.+/script>|
Did you wrap your regexp in forward slashes?
$str = preg_replace('/<script[\s\S]*?\/script>/', ...);
Did you surround your regular expression with a delimiter, such as /? If you didn't, you need to. If you did, and you used / (as opposed to your other choices) you'll need to escape the / in your /script, so it'll look like \/script instead.
Use the following code :
$result = preg_replace('%<script[\s\S]*?/script>%', $change_to, $subject);

JavaScript equivalent of PHP preg_split()

Is there an equivalent of the PHP function preg_split for JavaScript?
Any string in javascript can be split using the string.split function, e.g.
"foo:bar".split(/:/)
where split takes as an argument either a regular expression or a literal string.
You can use regular expressions with split.
The problem is the escape characters in the string as the (? opens a non capturing group but there is no corresponding } to close the non capturing group it identifies the string to look for as '
If you want support for all of the preg_split arguments see https://github.com/kvz/phpjs/blob/master/_workbench/pcre/preg_split.js (though not sure how well tested it is).
Just bear in mind that JavaScript's regex syntax is somewhat different from PHP's (mostly less expressive). We would like to integrate XRegExp at some point as that makes up for some of the missing features of PHP regexes (as well as fixes the many browser reliability problems with functions like String.split()).

php equals regular expression

I know I can use preg_match but I was wondering if php had a way to evaluate to a regular expression like:
if(substr($example, 0, 1) == /\s/){ echo 'whitespace!'; }
PHP does not have first-class regular expressions.
You will need to use the functions provided by the default PCRE extension. Sorry. It's a backslash-escaping nightmare, but it's all we've got.
(There's also the now-deprecated POSIX regex extension, but you should not use them any longer. They are slower, less featureful, and most important, they aren't Unicode-safe. Modern PCRE versions understand Unicode very well, even if PHP itself is ignorant about it.)
With regard to the backslash-escaping nightmare, you can keep the horror to a minimum by using single quotes to enclose the string containing the regex instead of doubles, and picking an appropriate delimiter. Compare:
"/^http:\\/\\/www.foo.bar\\/index.html\\?/"
versus
'!^http://www.foo.bar/index.html\?!'
Inside single quotes, you only need to backslash-escape backslashes and single quotes, and picking a different delimiter avoids needing to escape the delimiter inside the regex.
:)
if(substr($example, 0, 1) == " "){ echo 'whitespace!';}
You should not be using regexp when it is not needed.
There would also be the microoptimization option:
if (strstr(" \t\r\n", $example{0})) {
The {0} is an outdated way to get the first character (same as [0] actually). And strstr simply checks if the character is contained in the list of whitespace characters. Another option would be strspn, at least in your example case.

Grubers new and improved URL recognising regex

I've been trying to use grubers latest url matching regex in a php project.
To test it I threw together something very simple:
$regex = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:"'.,<>?«»“”‘’]))";
$array = pret_match_all($regex, $theblockofurltext);
print_r($array);
The first problem was the " would escape a string, depending which I wrapped the regex with, so I just removed it. The use of this is personal and I will never have " anywhere near a url anyway. This left me with a new regex.
$regex = "(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'.,<>?«»“”‘’]))";
Raring to go I then ran my little script and it gave me the following error:
Warning: preg_split() [function.preg-split]: Unknown modifier '\' in D:\wwwroot\xxx\index.php on line 14
Unfortunately my REGEX class at school wasn't taught to anywhere near the levels of this regex requires, and I have no idea where to begin fixing this for use with PHP. Any help would be greatly appreciated. No doubt I'm probably doing something stupid too, so please go easy on me :)
Jon
Add # before and after your RE.
$regex = "#(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'.,<>?«»“”‘’]))#";
If you use PCRE, the regular expression must be enclosed in delimiters. Now, parenthesis () can also be delimiters, that is why the engine thinks, your expression is only (?i) and interprets the next \ as modifier.
You could use ~ as delimiter:
$regex = "~(?i)\b...]))~";
Update:
I don't know whether PHP supports the partial modifying of an expression with (?i). So you might have to remove this and put the modifier after the delimiter instead (you apply it to the whole expression anyway):
$regex = "~\b...]))~i";

Categories