Re: dollars sign in regular expressions

From: Date: Wed, 16 Aug 2000 11:50:41 +0000
Subject: Re: dollars sign in regular expressions
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-11968@lists.php.net to get a copy of this message
Glen Ogilvie writes: > Hi, > > I am having difficulty understanding how to do the following RE, so anyone that > can explain, I would much appreicate it. > <? > $testval = 'this $name is a damn hard test <reason> because </reason'; > \\ $year = preg_replace ("'\141', "G", $testval); > $year = ereg_replace ("\044", "G", $testval); > print "<html><body>testval: $testval, $year</body></html>"; > ?> > > I am trying to replace the $ sign in this string with the letter G > This is so that I can use $name in an HTML file, read the file, and then > replace $name with a string value. For example > $name = "Glen"; > $year = preg_replace ("'\044.+\W'", $name, $testval); > > Thanks to everyone that looks at this problem. > > Glen Ogilvie > New Zealand It's not necessary to use the full power of a regular expression engine here; just use str_replace() to replace the dollar signs. And you can keep PHP from thinking that the dollar sign is the beginning of a variable name either by escaping the dollar sign inside the string with a backslash, or by using single quotes around the string instead of double quotes. Also, the output will likely not be what you expect unless you run it through htmlspecialchars() or something similar first; the angle brackets in the original string will make the resulting text invisible in your browser (though you could still see it with View Source). For instance: <?php error_reporting(E_ALL); $testval = 'this $name is a damn hard test <reason> because </reason>'; $year = str_replace('$', 'G', $testval); print("<html><body>testval:" . htmlspecialchars($testval) . ", " . htmlspecialchars($year) . "</body></html>"); ?> Cheers, Torben -- +----------------------------------------------------------------+ |Torben Wilson <torben@php.net> Netmill iTech| |http://www.coastnet.com/~torben http://www.netmill.fi| |Ph: 1 250 383-9735 torben@netmill.fi| +----------------------------------------------------------------+

« previous php.general (#11968) next »