homepage Welcome to WebmasterWorld Guest from 23.20.91.134
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
value between square brackets
ahmed24




msg:4048937
 3:04 pm on Dec 24, 2009 (gmt 0)

I have a string called $title that contains a random value in square brackets like this: [12A]. can anyone tell me how i can fetch this value in between the open and close square bracket?

thanks

 

mooger35




msg:4048982
 5:13 pm on Dec 24, 2009 (gmt 0)

Sounds like a regex solution is needed... try something like this:

$title = "string[12B]";
preg_match("/\[(.*)\]/", $title , $matches);

echo $matches[1];


ahmed24




msg:4048988
 5:46 pm on Dec 24, 2009 (gmt 0)

thanks. works perfect

TheMadScientist




msg:4052427
 12:40 am on Jan 1, 2010 (gmt 0)

Although the posted solution works, depending on the length of the entire string involved it ranges from slightly inefficient to beyond the time most have to do the math for to determine the lack of efficiency...

I would recommend:
preg_match("/\[([^\]]+)\]/", $title , $matches);

Which matches [, followed by 'IsNotABracket', followed by ].

The reason is if the string you are trying to find the match in continues beyond the closing bracket the .* matches the entire string, then has to work backward and forward until all possible matches are found, then the best match is chosen... For more detailed information, see the linked thread or the PHP preg manual.

[webmasterworld.com...]

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved