Jump to content

Help with regex?


jekillen

Recommended Posts

Hello;

 

I have been doing php for some time and I had initially become somewhat

knowledgable on how to use create and use regular expressions (with the

old regex funtions). But I have been avoiding regex as slow, in favor of designs

that would allow string manipulation functions where and when ever possible.

 

But there are situations where it is un avoidable, as now:

 

I am working on an html base text editor. The text to be edited is loaded into

a textarea element in the editors html. If the text to be edited is a php and/or

html/javascript code file, there are cases where there are escaped dollar signs

inside of double quotes.

 

I want to find instances of escaped dollar signs (\$) inside of double quoted

strings only, and add an extra escape to the $, so it becomes "....\\$...." instead

of "....\$...."

 

Here is what I have so far, but it seems to be removing everything but the $ in

initial testing:

 

$_testStr = "do you want \$_ref, or do you want $_ref?";
$_testStr = preg_replace("/\".*(\\$).*\"/", '\\$', $_testStr);

 

So, in this function, how to I reference and replace only what

is matched by the sub pattern? I am having much difficulty

understanding the php online manual regarding this.

 

Do I have to do preg_match() first and then use the $n reference as the replacement?

 

Thanks for time and attention

Link to comment
Share on other sites

In original post I neglected to include an embedded double quote set around \$_ref

 

I got what I am looking for:

 

$_ref = 'help';
$_testStr = "do you want \" \$_ref \", or do you want $_ref?";
preg_match('/(\".*(\\$).*\")/', $_testStr, $_match);
$_alt = str_replace($_match[2], '\\$', $_match[0]);
$_testStr .= "\n".str_replace($_match[0], $_alt, $_testStr);

in html
... etc..
<pre>
<textarea >
do you want " $_ref ", or do you want help?
do you want " \$_ref ", or do you want help?
</textarea>
<spam><code>
do you want " $_ref ", or do you want help?
do you want " \$_ref ", or do you want help?
</code></span>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...