Showing posts with label split string using array in php. Show all posts
Showing posts with label split string using array in php. Show all posts

Monday, March 26, 2012

PHP: Split string using array

Example 1:
<?php
 $str = "How are you doing today?";
 $split_str = explode(" ", $str);
 echo '<pre>'.print_r($split_str, true).'</pre>'; // Output 1
 echo $split_str[1]; // Output 2
?>
Output 1
Array
(
    [0] => How
    [1] => are
    [2] => you
    [3] => doing
    [4] => today?
)
Output 2
are

Example 2:
<?php
$string = '<span style="font-weight: bold;">Lorem ipsum dolor sit amet:-</span><br>(1) consectetur adipisicing elit <br>(2) sed do eiusmod tempor <br>(3) incididunt ut labore et <br>(4) dolore magna aliqua';
echo '<p>'.$string.'</p>'; // Output 3

$chars = preg_split('/<br>/', $string, -1, PREG_SPLIT_OFFSET_CAPTURE);
$third_br_position = $chars[3][1];  
$description = substr($string, 0, $third_br_position);

echo '<p>'.$description.'</p>'; // Output 4
?>
Output 3
Lorem ipsum dolor sit amet:-
(1) consectetur adipisicing elit 
(2) sed do eiusmod tempor 
(3) incididunt ut labore et 
(4) dolore magna aliqua
Output 4
Lorem ipsum dolor sit amet:-
(1) consectetur adipisicing elit 
(2) sed do eiusmod tempor 

Refer site:
explode() - http://php.net/manual/en/function.explode.php
preg_split() - http://php.net/manual/en/function.preg-split.php
http://www.java-samples.com/showtutorial.php?tutorialid=938