At 10:16 PM 1/5/2002 -0500, Gerard Samuel wrote:
>Need some help with this one.  Dont know where to begin.  I have content 
>in a string and a constant that changes depending on if yourre in the root 
>or in a directory.
>The purpose of the constant is to provide dynamic links.
>The string will have href links like <a href="index.php">Index</a>
>I want to figure out a way to inject my constant value into the href like so
><a href="'._CONSTANT'index.php">Index</a>
>I would like the rules to say,
>If string contains <href="> and there are <alphanumerical chars> .php 
>place _CONSTANT between <href="> and <alphanumerical chars>
>I figure a regular expression, but I have no idea where to start..

This seems to work:

<?
define("_CONSTANT","/path/");

$string = "Click <a href=\"index.php\">here</a> to return to the main page.";

echo insertpath($string);

function insertpath($string) {

         return preg_replace("/(<a 
href=\")(.*\">.*<\/a>)/i","$1"._CONSTANT."$2",$string);

}
?>

Preg_replace allows you to use backreferences and access them via variables 
such as $1 and $2, etc.  Earlier versions of PHP required you to use \\1, 
\\2 instead (see the documentation for preg_replace for more info).  Each 
section of the regex that is in parenthesis can be accessed.  In the above 
example, the (<a href=\") section is reprinted in the replacement string by 
using $1, so on a so forth.  The ".*" in the regex basically means match 
"any old junk" since the "." refers to any single character and the "*" 
means match the previous character zero or more times.

http://download.php.net/manual/en/function.preg-replace.php


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to