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? 

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.