Reputation: 18123
The usual:
$data = 'hello world&cool&stuff&here';
$explode = explode('&', $data); // returns array with hello world, cool, stuff, here
Now this data
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
How can i extract "The World is Beautiful" from the above string?
Running explode('#content_start', $data);
and then explode('#content_end', $data);
? Or is there an easier and more fit way.
Upvotes: 0
Views: 67
Reputation:
Try THIS....
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
echo substr(strstr(implode(explode("end#",implode("{",explode("start#", implode(explode("#content_", $data)))))), '{'), 1);
Upvotes: 1
Reputation: 3120
The idea you had would work perfectly fine.
Just do it like that:
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
$first = explode('#content_start#', $data);
$second = explode('#content_end#', $first[1]);
echo $second[0];
The first explode will return an array of strings, where the first ($first[0]
) will be hey this is a beautiful day
and the second ($first[1]
) will be The World is Beautiful#content_end#
. Then you can use the second explode to have the result you wanted.
However, a more readable approach would be to use a RegEx to match your searched pattern and literally search for your string. The code would then be:
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
$matches = array();
preg_match('/#content_start#(.*)#content_end#/', $data, $matches);
echo $matches[1];
Upvotes: 1
Reputation: 3692
This is a job for regular expressions:
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
preg_match( '/#content_start#(.*)#content_end#/s', $data, $matches );
print_r( $matches );
This will display:
Array
(
[0] => #content_start#The World is Beautiful#content_end#
[1] => The World is Beautiful
)
So $matches[0]
contains the original matched string, and $matches[1]
contains the match.
Upvotes: 0
Reputation: 4190
Using explode
is not the best option here.
You should better use strpos
and substr
:
$start = '#content_start#';
$end = '#content_end#';
$startPos = strpos($data, $start) + strlen($start);
$length = strpos($data, $end) - $startPos;
$result = substr($data, $startPos, $length);
Upvotes: 0
Reputation: 158220
Why not using this?
$data = 'hey this is a beautiful day #content_start#The World is Beautiful#content_end#';
$parts = explode('#', $data);
echo $parts[2];
Upvotes: 0