0

I have this array:

 $form = array(
    array(
       "type" => "text",
       "value" => "
         Hello @name

         How old are you? @age

         How are you today? @condition"
    ),
    array(
       "type" => "font",
       "family" => "Arial",
       "size" => 6,
       "weight" => "Bold"
    )
 );

Then I did this json_encode($form) and It has this output:

 [ 
  {
   "type":"text",
   "value":"\r\n Hello @name\r\n\r\n How old are you? @age\r\n \r\n How are you today? @condition"
  },
  {
   "type":"font",
   "family":"Arial",
   "size":6,
   "weight":"Bold"
  }
 ]

The thing is json_encode() also acts like a string so I can also do like this:

 $old = array('@name','@age',@condition');

This $old data is what I will put in the str_replace();

But I want to do it in an array form like get all data with @ symbol.

Can we do that with pregmatch? or is there any other way to do it?

2
  • in str_replace yu can pass array as well. Commented Jun 4, 2018 at 5:38
  • yeah i already done that sir, but I wanted it to be like dynamic or something to get all the data @ signs on it Commented Jun 4, 2018 at 5:40

1 Answer 1

1

Yes, You can get list of words that start with @ by using preg_match
I would use a function like this to help me get data from any type of input :

/**
* We will take two param on this function
* $input is the data we will be look into
* $tags is reference to a array, we will store out result in this array.
*/
function fetch_tags($input, &$tags){
    if(is_array($input)){
        // If input is array, iterate it and pass the value to fetch_tags function
        foreach($input as $key => $value ){
            fetch_tags($value, $tags);
        }

        return true;
    }elseif(is_string($input)){
        /**
        * If its a string, we can preg_match now.
        * \@\S+ means we will take any string which follows a @
        * If we get any matches, we will store that result in $tags
        */
        if(preg_match_all('#(\@\S+)#', $input, $matches)){
            $tags = array_merge($tags, $matches[1]);
        }

        return true;
    }
    return false;
}

Example :

<?php

$form = array(
    array(
       "type" => "text",
       "value" => "
         Hello @name

         How old are you? @age

         How are you today? @condition"
    ),
    array(
       "type" => "font",
       "family" => "Arial",
       "size" => 6,
       "weight" => "Bold"
    )
 );

$words = [];

fetch_tags($form, $words);

print_r($words);

Output would be :

Array
(
  [0] => @name
  [1] => @age
  [2] => @condition
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot mate! :)

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.