I have a taken a tree input as PHP string
e.g ((APPLE MANGO)(BALL BAT))
I have an application in which the users select a REFERENCE object. In this example if the user selects BALL as reference object, then my string must become
((BALL MANGO)(APPLE BAT))
i.e the REFERENCE object and the first object must be swapped…
Please suggest some solutions. How can i manipulate this string using PHP.
And the structure is always like this?
((word1 word2)(word3 word4))
I’d say first you’d have to get the four words in an array. With preg_match() for example:
$words = preg_match('/\\(\\((.*?) (.*?)\\)\\((.*?) (.*?)\\)\\)/', '((APPLE MANGO)(BALL BAT))');
This will give this result:
 => ((APPLE MANGO)(BALL BAT))
 => APPLE
 => MANGO
 => BALL
 => BAT
So if you ignore the first element, the next four will contain the four words.
Now all you have to do is find the reference object, and swap it with the first object, and then recreate the string.
Thank you for the suggestion, but my problem is regarding the reconstruction of the string. As i dont know how many objects will be there in the string and how many braces. So i am unable to insert braces between the objects
Well, lets try and define the tree. What I see in your tree is:
/ \\ / \\
3 4 5 6
Where 0,1,2 are empty, 3,4,5, and 6 are the words.
Is this true? Is this tree always going to be empty except for the leaves?
Assuming that’s the structure, then [FPHP]preg_split[/FPHP] the string on “( or \s”, capturing the delimiter. That will deconstruct your string. Find the first non-parenthesis index, find your target index, set the target index to the value at the first index, then set the first index to your target, and implode the array over ‘’.