0

I wrote the regex expression like this

^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$

Which is checking the the string is symbol only

I use the checker to check that the regex is correct.

Then I put it into my php code

$regex = "^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$";
$regex = '^[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]+$';

Both I tried and its not work because the quote is broken by the quote in the regex.

I don't want to concat them like

$regex="{partA}".'"'."{partB}";

I think this is too difficult to read and not easy to maintenance

How do I solve this problem?

Emma
  • 27,428
  • 11
  • 44
  • 69
Pete
  • 170
  • 1
  • 13

3 Answers3

1

Both of your regexes produce syntax errors in PHP due to there being quotation marks inside of the regex itself.

If you don't want to concatenate the regex into two different parts, your best approach is to escape the quotation marks with backslashes:

$regex = "^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+$";
$regex = '^[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]+$';

Note that the latter is more preferable, as double quotes will parse any variables stored within the string; if there were any text after the $, and a corresponding variable, the variable's content would be injected into the regex:

$sample = 'text';
$regex = "^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+$sample";

echo $regex;
// ^[-!$%^&*()_+|~=`{}\[\]:\";'<>?,.\/]+text

In addition to this, it's also slightly faster to use single quotes.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

For your first expression, here we can use \x27 and \x22 instead of quotes, and we might want to remove the start and end chars, maybe similar to:

[-!$%^&*()_+|~=`{}\[\]:\x22;\x27<>?,.\/]+

enter image description here

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Or if I understand correctly, another alternative would be to collect all chars in the first capturing group, then save our desired alphanumeric in the second one, maybe similar to:

([\s\S].*?)([a-z0-9]+)?

enter image description here

Test

$re = '/([\s\S].*?)([a-z0-9]*)/mi';
$str = '{partA}".\'"\'."{partB}{partC12}".\'"\'."{partD109}{partA}".\'"\'."{partB}{partC12}".\'"\'."{partD109}';
$subst = '$2 ';

$result = preg_replace($re, $subst, $str);

echo $result;

const regex = /([\s\S].*?)([a-z0-9]*)/gmi;
const str = `{partA}".'"'."{partB}{partC12}".'"'."{partD109}{partA}".'"'."{partB}{partC12}".'"'."{partD109}`;
const subst = `$2 `;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

DEMO

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69
0

Maybe your regular expression can be as simple as ^(?!.*[#\\@])[[:punct:]]+$?
[:punct:] is one of POSIX Bracket Expressions.
Demo and explanation at https://regex101.com/r/4XnUzW/1/.

Andrei Odegov
  • 2,925
  • 2
  • 15
  • 21