Welcome to WebmasterWorld Guest from 54.226.32.234

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

regex: get value

     

camilord

3:03 am on Mar 28, 2014 (gmt 0)

5+ Year Member



hi.. need help again with regex...

hope readie will be posting his answer here.. hehee..

this is the string...

PRETTY_NAME="Kali GNU/Linux 1.0"
NAME="Kali GNU/Linux"
ID=kali
VERSION="1.0"
VERSION_ID="1.0"
ID_LIKE=debian
ANSI_COLOR="1;31"
HOME_URL="http://www.kali.org/"
SUPPORT_URL="http://forums.kali.org/"
BUG_REPORT_URL="http://bugs.kali.org/"


i need to extract the value of NAME or PRETTY_NAME...

what would be the pattern?

camilord

9:57 am on Mar 28, 2014 (gmt 0)

5+ Year Member



got the solution already... :)

preg_match_all('/(\w+)\s*=\s*(["\'])((?:(?!\2).)*)\2/', $this->_server_data['lsb'], $result, PREG_SET_ORDER);
if (isset($result[0][3])) {
return $result[0][3];
}

Readie

12:56 pm on Mar 28, 2014 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Would have posted an answer :P

camilord

7:02 pm on Mar 28, 2014 (gmt 0)

5+ Year Member



hhehehe... anyway.. thanks Readie...

penders

10:59 pm on Mar 28, 2014 (gmt 0)

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



If you just need to match the value of PRETTY_NAME (or any single field), can this not be simplified to something like:

preg_match('/PRETTY_NAME="(.+?)"/', $this->_server_data['lsb'], $result);
return isset($result[1]) ? $result[1] : false;


?

robzilla

1:05 am on Mar 29, 2014 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



If PRETTY_NAME is always present, and the value is all you need, you could avoid regular expressions like so:

$prettyname = trim(str_replace('"','',str_replace('PRETTY_NAME="','',substr_replace($string,'',strpos($string,"\n")))));


Where strpos finds the position of the first linebreak, substr_replace then removes everything that comes after that position, str_replace then removes PRETTY_NAME=" at the front of the remaining string and the closing " at the end. If PRETTY_NAME is not always present, you could add another str_replace for NAME=":

$prettyname = trim(str_replace('"','',str_replace('NAME="','',str_replace('PRETTY_NAME="','',substr_replace($string,'',strpos($string,"\n"))))));


Though if you prefer to use preg_match, the simplest expression I could come up with is this:

preg_match('#(PRETTY_)?NAME="(.+)"#',$string,$match);


Where the value of PRETTY_NAME or NAME (whichever comes first) would then be stored in $match[2].

However, it's best to avoid regular expressions when you can. I ran both methods 10 million times, and the first method was at least 4x faster than preg_match.
 

Featured Threads

Hot Threads This Week

Hot Threads This Month