Extracting Single Lines Using Regex
Hello,
Suppose I have the following script:
Set Variable [ $list ; List ( "apple|red" ; "banana|yellow" ; "grape|white" ) ]
Set Variable [ $pattern ; "/^banana.*$/i" ]
Set Variable [ $match ; Regex.MatchAll ( $list ; $pattern ) ]
where Regex.MatchAll ( _text ; _pattern ) is the following custom function:
Let (
[
$fm_text = _text ;
$fm_pattern = _pattern ;
_code =
"
$text = fm_evaluate ('$fm_text');¶
$pattern = fm_evaluate ('$fm_pattern');¶
preg_match_all ($pattern, $text, $matches);¶
echo join(\"\n\", $matches[0]);¶
"
] ;
PHP_Execute( _code )
)
I'm expecting the entire line "banana|yellow" to be returned, but instead $match is empty. Any ideas?
There certainly might be a problem with my custom function. Maybe in version 2.0 of your PHP plugin you can wrap some common PHP tasks in FMP external functions? ;o)
Regards,
Sean
A Different Custom Function
After thinking about my problem some more, I came up with a slightly different custom function, called Regex.MatchLines
Regex.MatchLines ( _list ; _pattern )
Let (
[
$fm_list = _list ;
$fm_pattern = _pattern ;
_code =
"
$list = fm_evaluate('$fm_list');¶
$pattern = fm_evaluate('$fm_pattern');¶
$array = preg_split(\"/\r/\", $list);¶
$matches = preg_grep($pattern, $array);¶
echo join(\"\r\", $matches);¶
"
] ;
PHP_Execute( _code )
)
I'm converting the return-delimited list into a PHP array (preg_split) and then searching the array for items that match the supplied pattern (preg_grep). Any search results are placed in an array, which is then converted back to a return-delimited list.
--
Regards,
Sean Mills
Grantwood Technology LLC
http://www.grantwoodtechnology.com
Works like a charm
Gave it a quick try here and it works great.
Regards,
Micah
"Explode" Instead of "Preg_Split"
Not sure if it makes a difference, but changing:
$array = preg_split(\"/\r/\", $list);¶
to
$array = explode(\"\r\", $list);¶
works as well.
--
Regards,
Sean Mills
Grantwood Technology LLC
http://www.grantwoodtechnology.com/grantwood_contact.html