nicolem798 Posted December 26, 2008 Share Posted December 26, 2008 Hello I have a long variable similar to the following ... $data=" text text text house cars [ball] test boat [one two three] ball toy text text a lot of text [nice ball] other text"; I would extract from $data and put on $test array only the text which is between [] . So in the example above I would have an array with 3 values [0] ball [1] one two three [2] nice ball Anyone can help me to code this ? Thank you Quote Link to comment https://forums.phpfreaks.com/topic/138469-extracting-useful-data-from-text/ Share on other sites More sharing options...
Serenitee Posted December 26, 2008 Share Posted December 26, 2008 What you are looking for is regex I believe. While I'm quite sure someone else can do this more gracefully (and possibly more "correct" as I am still learning): preg_match_all("/\[(.+?)\] (.+?) \[(.+?)\] (.+?) \[(.+?)\] (.+?)/", $data, $test); echo '<pre>'; echo print_r($test); echo '</pre>'; This will return an array with each sentence bit separated, and the 1, 3, 5 sections are the information you would need: Array ( [0] => Array ( [0] => [ball] test boat [one two three] ball toy text text a lot of text [nice ball] o ) [1] => Array ( [0] => ball ) [2] => Array ( [0] => test boat ) [3] => Array ( [0] => one two three ) [4] => Array ( [0] => ball toy text text a lot of text ) [5] => Array ( [0] => nice ball ) [6] => Array ( [0] => o ) ) 1 Hope this helps, or at least points you in a direction Quote Link to comment https://forums.phpfreaks.com/topic/138469-extracting-useful-data-from-text/#findComment-723993 Share on other sites More sharing options...
DarkWater Posted December 26, 2008 Share Posted December 26, 2008 <?php $string = " text text text house cars [ball] test boat [one two three] ball toy text text a lot of text [nice ball] other text"; preg_match_all('/\[([^\]]+)\]/', $string, $matches); print_r($matches); ?> $matches[1] will be a multidimensional array containing the strings you want. Quote Link to comment https://forums.phpfreaks.com/topic/138469-extracting-useful-data-from-text/#findComment-723995 Share on other sites More sharing options...
Serenitee Posted December 26, 2008 Share Posted December 26, 2008 I knew someone could come along and clean that up! Quote Link to comment https://forums.phpfreaks.com/topic/138469-extracting-useful-data-from-text/#findComment-724005 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.