Forum Moderators: coopster

Message Too Old, No Replies

Regex Help!

         

almo136

2:59 am on Oct 17, 2009 (gmt 0)

10+ Year Member



Hi,

I have a script which has this regex in it:

preg_match_all('/((#?[A-Za-z0-9]+))/'

This takes a line of text like and strips out all the characters apart from the color code. For example it turns this:
Black (#000000)
into this:
#000000

I would like to change it so that instead of extracting the color it would extract anything included in the brackets. For example it would turn this:
Black (/magento/1.gif)
into this:
/magento/1.gif

Thanks!

OscarHiboux

3:45 am on Oct 17, 2009 (gmt 0)

10+ Year Member



preg_match('/\w+\s*\((.+)\)/', 'Black (/magento/1.gif)', $capture);
var_dump($capture);

giving:

array(2) {
[0]=>
string(22) "Black (/magento/1.gif)"
[1]=>
string(14) "/magento/1.gif"
}

skinsey

4:20 am on Oct 17, 2009 (gmt 0)

10+ Year Member



Maybe this might help a bit.

<form method ="post" action ="test.php">
<input type ="text" name="name"/>
<input type ="submit" value ="submit"/>
</form>
<?
$string = $_POST["name"];
$length = strlen($string);
$right = strrpos($string, "(");
$left = strrchr($string, ")");
$start = $right - $length;
$end = $left - $right;
$value = substr($string, $start, $end);
echo $value;
?>

skinsey

4:29 am on Oct 17, 2009 (gmt 0)

10+ Year Member



just tested it, it should be

<form method ="post" action ="test.php">
<input type ="text" name="name"/>
<input type ="submit" value ="submit"/>
</form>
<?
$string = $_POST["name"];
$length = strlen($string);
$right = strrpos($string, "(");
$left = strrchr($string, ")");
$start = $right - $length +1;
$end = $left - $right - 1;
$value = substr($string, $start, $end);
echo $value;
?>

rocknbil

4:50 pm on Oct 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




<html><head><title>test</title></head><body>
<p><em>I would like to change it so that instead of extracting the
color it would extract anything included in the brackets.</em></p>
<?php
$tests = Array (
'Black (#000000)',
'Black (/magento/1.gif)',
'(leading bracket) and some more',
'start with more (and a trailing bracket)',
'I am the (Egg Man)',
'I am the Walrus (co coo - cachoo)'
);
echo '<p>Before:</p>';
foreach ($tests as $v) {
echo "$v<br>\n";
}
echo '<p>After:</p>';
foreach ($tests as $v) {
// Zero or more of ANY character followed by (
// followed by zero or more of any character NOT a )
// followed by zero or more of any character.
// Store what's in the unescaped () in $1
$v = preg_replace('/.*\(([^\(]*)\).*/',"$1",$v);
echo "$v<br>\n";
}
echo '</body></html>';
?>

results

#000000
/magento/1.gif
leading bracket
and a trailing bracket
Egg Man
co coo - cachoo

There are problems with this pattern if there's a ( before or after your (), but in the case of style sheets, I think not.