Jump to content

[SOLVED] Extract part of a string (difficult)


alste450

Recommended Posts

Hi,

 

I have a string:

 

$string =

"John{

[string I wanna extract]

}

 

Nancy{

[string I don't wanna extract]

}";

 

 

I am looking for a code that can extract the string in between the brackets { } that correspond to John only. How can I do this?

 

Thanks for your help!

You can do it with regular expressions/PCRE. Give more information:

 

1) Is "John" always the first thing and that's what you want to grab?

 

2) or the word "John" is the important part?

 

3) I assume the contents within {} can span multiple lines, right?

 

 

I'm moving topic to regex help.

 

<?php

$string =
"John{
[string I wanna extract]
}

Nancy{
[string I don't wanna extract]
}";

/**
* You can take of "John" out of the expression if it's always first
* and it will still work as long as you just look at the first result
*/
//if (preg_match_all('/\John{(.+?)\}/s', $string, $arrResult)) {
if (preg_match('/\John{(.+?)\}/s', $string, $arrResult)) {
    
    echo $arrResult[1];    // Use with preg_match()
//  echo $arrResult[1][0]; // Use with preg_match_all()
//  echo '<pre>', print_r($arrResult, TRUE), '</pre>'; // Displays all results

} else {
    
    echo 'No match found';
}


?>

Hi toplay,

 

The function of the code I'm looking for is to grab everything in between the brackets corresponding to a certain variable ($name).

 

For example, if my string is

 

$string =

"John{

john is a brown worm

}

 

Laura{

nancy is a blue pig

}";

 

and $name = "John", what I want returned is "john is a brown worm";

$name can equal Laura too, or any other name, in a list of n names, so John doesn't have to be the first name.

And the contents within the brackets can span multiple lines.

 

I am trying to do it with preg_match but it's not working.

 

Thanks for you help!

OK, then you can do something like this:

 

You can remove the 'i' option in the preg_match() if you want to search to match the case exactly.

 

<?php

$string =
"John{
[string I wanna extract]
}

Nancy{
[string I don't wanna extract]
}";

$name = preg_quote('john');

if (preg_match('/' . $name . '\{(.+?)\}/si', $string, $arrResult)) {
    
    echo $arrResult[1];    // Use with preg_match()
//  echo $arrResult[1][0]; // Use with preg_match_all()
//	echo '<pre>', print_r($arrResult, TRUE), '</pre>';

} else {
    
    echo 'No match found';
}


?>

 

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.