Jump to content

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/138469-extracting-useful-data-from-text/
Share on other sites

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

 

<?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.

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.