Page 1 of 1

preg_match_all help...

Posted: Wed Sep 14, 2005 12:03 am
by Mr Tech
I have peices of text on the page... Go example:

Code: Select all

{ADDCART:[Rug Only 4|9||-5|6||]PRICE:[82.00]}
{ADDCART:[Rug Only 5|9||-6|]PRICE:[87.00]}
I want to select those and replace with a link... E.g:

Code: Select all

<a href="products/order/cart.php?mode=add&item=Rug%20Only%204|9||-5|6||&price=82.00">Add to Cart</a>
<a href="products/order/cart.php?mode=add&item=Rug%20Only%205|9||-6|&price=87.00">Add to Cart</a>
I tried this code but it aint working...

Code: Select all

$match_count = preg_match_all("#\{ADDCART:\[(.*?)\]PRICE:\[(.*?)\]}#si", $body, $matches);
for ($i = 0; $i < $match_count; $i++)
{
	$original = "";
	$replace = "";
	$original = "{ADDCART:[$matches[0]]PRICE:[$matches[1]]}";
	$replace = "<a href=\"products/order/cart.php?mode=add&item={$matches[0]}&price={$matches[1]}\">Add to Cart</a>";

	$body = str_replace($original, $replace, $body);
}
What am I doing wrong?

Posted: Wed Sep 14, 2005 12:09 am
by feyd
each element of $matches is an array of the corresponding matches found in the pattern.

print_r($matches);


Moved to Regex.

Posted: Wed Sep 14, 2005 12:15 am
by Mr Tech
But haven't I requested the text from the array using $matches[0]?

And also, do you know what's wrong with this code:

Code: Select all

$match_count = preg_match_all("#\{ADDCART:\[(.*?)\]PRICE:\[(.*?)\]}#si", $body, $matches);
It's not picking up anything...

Posted: Wed Sep 14, 2005 12:37 am
by Mr Tech
I think I found the problem... It was replacing the [ with &#xxx and stuffing up the script... I'll make asure everything is working and post if I have anymore dramas

Posted: Wed Sep 14, 2005 12:56 am
by feyd
$matches[0] is an array of the full strings matching the pattern.
$matches[1] is an array of group 1's captures found in the pattern of the corresponding full string.
$matches[2] is an array of group2's captures found in the pattern of the corresponding full stirng.

Code: Select all

[feyd@home]>php-cgi
<?php
$body = "{ADDCART:[Rug Only 4|9||-5|6||]PRICE:[82.00]}
{ADDCART:[Rug Only 5|9||-6|]PRICE:[87.00]}";
$match_count = preg_match_all("#\{ADDCART:\[(.*?)\]PRICE:\[(.*?)\]}#si", $body, $matches);
var_export($matches);
?>
^Z
Content-type: text/html
X-Powered-By: PHP/5.0.4

array (
  0 =>
  array (
    0 => '{ADDCART:[Rug Only 4|9||-5|6||]PRICE:[82.00]}',
    1 => '{ADDCART:[Rug Only 5|9||-6|]PRICE:[87.00]}',
  ),
  1 =>
  array (
    0 => 'Rug Only 4|9||-5|6||',
    1 => 'Rug Only 5|9||-6|',
  ),
  2 =>
  array (
    0 => '82.00',
    1 => '87.00',
  ),
)