Jump to content

[SOLVED] Very confusing Regex problem


lococobra

Recommended Posts

First off, yeah... I know there's a regex section, but no one responded to my previous question that was over there, so here I am...

 

So lets say I have some php code stored in a variable, I want to isolate all the strings in that code. Right now I'm using the following expression:

<?php
preg_match_all("/([\"'])(.*?)\\1/", $input, $strings);
?>

 

However, if you look carefully there's a problem... What if it encounters a string like this "I read an article called \"How To Use Regex\" it was very good". Obviously there's going to be some massive butchering of that string.

 

So what I need to do is make sure that the character directly before the end quote (\\1) is not a backslash (\\)

 

But here's a major problem... double backslash in a regular expression is not the same as a double backslash in say a string. How do I do this?

 

My best guess:

<?php
preg_match_all("/([\"'])(.*?)^\\?\\1/", $orig, $st_s);
?>

 

Please help!

 

Link to comment
https://forums.phpfreaks.com/topic/59764-solved-very-confusing-regex-problem/
Share on other sites

Thank you so much, that works great.

 

Actually, yours needed to be modified just a bit to make it work in 100% of cases...

 

"/([\"'])(.*?[^\\\]?)\\1/" Is what I ended up using (note the ? after [^\\\])

 

That was required so that strings like "" wouldn't kill it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.