0

In PHP, I have strings like so:

$string = "This is a 123 test (your) string (for example 1234) to test.";

From that string, I'd like to get the words inside the () with the numbers. I've tried using explode but since I have 2 word/group of strings enclosed in the parentheses, I end up getting (your) instead of (for example 1234). I've also used substr like so:

substr($string, -20)

This works most of the time but the problem with this is, there are instances that the string is shorter so it ends up getting even the unwanted string. I've also tried using regular expression in which I set something like so:

/[^for]/

but that did not work either. The string I want to get always starts with "for" but the length varies. How do I manipulate php so that I can get only the string enclosed inside the parentheses that starts with the word for?

1
  • Use preg_match for regular expression Commented Oct 3, 2013 at 1:08

4 Answers 4

3

I might use preg_match() in this case.

preg_match("#\((for.*?)\)#",$string,$matches);

Any matches found would be stored in $matches.

Sign up to request clarification or add additional context in comments.

Comments

2

Use the following regular expression:

(\(for.*?\))

It will capture patterns like:

(for)
(foremost)
(for example)
(for 1)
(for: 1000)

A sample PHP code:

$pattern = '/(\(for.*?\))/';
$result  = preg_match_all( 
    $pattern, 
    " text (for example 1000) words (for: 20) other words",
    $matches 
);

if ( $result > 0 ) {
    print_r( $matches );
}


Above print_r( $matches ) result:

Array
(
    [0] => Array
        (
            [0] => (for example 1000)
            [1] => (for: 20)
        )

    [1] => Array
        (
            [0] => (for example 1000)
            [1] => (for: 20)
        )
)

1 Comment

Thanks a lot for the help and for going a step further by giving an explanation of what happens in the regular expression.
1

Use preg_match for regular expression

$matches = array();
$pattern = '/^for/i';
preg_match($pattern,$string,$matches);
pirnt_r($matches);

If matches is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

Comments

0
$matches = array(); 
preg_match("/(\(for[\w\d\s]+\))/i",$string,$matches);
var_dump($matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.