Jump to content

[SOLVED] How to extrapolate words from a string


domenico

Recommended Posts

I have this string:

 

$string="bla bla sentence  (one) bla sentence (two) (three) bla bla bla (four)";

 

i would like to extract (one) (two)  (three) (four) and put them in an array.

 

Someone can show me some example with eregi() or non posix functions? 

 

 

Try something like the below.

 

<?php
$string = 'one and some text two and some text three and some text four and some text'; // The input string
$arr = array('one', 'two', 'three', 'four'); // Words to find
foreach ($arr as &$word) {
$RT_Code = '/.*(' . $word . ').*/s'; 
$WT_Code = '$1' . '<br>'; 
echo preg_replace($RT_Code, $WT_Code, $string); 
}
?>

 

Let me quickly cover the expression /.*(' . $word . ').*/s

 

The (dot) matches any character, while the star means that either there is something, in front of, or after the word we are looking for. If i used a plus sign "+", then it would only match words that had something before or after them. The parentheses remembers the match, so we can access this through "$1" later, which where done on the next line.

 

Finally the "s" modifier at the end makes the (dot) include newlines. You can use the "i" modifier as well to make an case insensitive search.

If you want to just match items in non-nested paired parens groups:

Raw Match Pattern:
(?<=\()[^)]*(?=\))

PHP Code Example:
<?php
$sourcestring="your source string";
preg_match_all('/(?<=\()[^)]*(?=\))/',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

$matches Array:
(
    [0] => Array
        (
            [0] => one
            [1] => two
            [2] => three
            [3] => four
        )

)

 

If you want to capture the parens as well:

preg_match_all('/\([^)]*\)/',$sourcestring,$matches);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.