how to use regular expression to find a value in a string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jasongr
Forum Contributor
Posts: 206
Joined: Tue Jul 27, 2004 6:19 am

how to use regular expression to find a value in a string

Post by jasongr »

Hello people

I have a string which may contain the following HTML attribute:
colspan="<value>"
for example: colspan="5"
I need to be able to extract the value of the colspan value if one exists under the following conditions:
1) the colspan phrase is case insensitive
2) the double quote could be single quote or no quotes at all
3) the string may end after the colspan attribute or it may have other attributes (which I don't care about). If there are other attributes after the colspan, at least one whitespace character can be assumed after the colspan value

The following are some valid examples:
colspan="5"
colspan='5'
COLspan="5"
COLspan=5
colspan='5' width="4"
colSPAN=5 nowrap

I would appreciate it if someone could help me with this as I am new to regular expression

regards
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php

$text = 'jcolspan =''5'' colspan=      " 23   "';
preg_match('#(?<!\w)colspan\s*=\s*(&#1111;"'']?)\s*(.*?)\s*\\1#si', $text, $match);
print_r($match);

?>

Code: Select all

Array
(
    &#1111;0] => colspan=      " 23   "
    &#1111;1] => "
    &#1111;2] => 23
)
Post Reply