Siska Brilian
Siska Brilian

Reputation: 61

Split word from string using PHP

I tried to split the characters from the available string, but have not found the right way.

I have a string like below :

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
foreach ($k as $l) {
    var_dump(substr_replace($tara, '', $i, count($l)));
}

The result I want is :

'wordpress',
'wordpress/corporate',
'wordpress/corporate/business'

Upvotes: 2

Views: 91

Answers (5)

Krzysztof Raciniewski
Krzysztof Raciniewski

Reputation: 4924

You should explode your string array and print in foreach all exploded values using implode and temporary array(for example). Here is working code:

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$tmp = [];

foreach ($k as $l) {
    $tmp[] .= $l;
    var_dump(implode($tmp, '/'));
}

Upvotes: 1

sujeet pandit
sujeet pandit

Reputation: 131

Try This, Its Easiest :

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$str = array();
foreach ($k as $l) {
   $str[] = $l;
   echo implode('/',$str)."<br>";
}

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67495

You could concatenate in every iteration like :

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$result = "";

foreach ($k as $l) {
    $result .= '/'.$l;
    echo $result."<br>";
}

The output will be :

/wordpress
/wordpress/corporate
/wordpress/corporate/business

If you don't need the slashes at the start you could add a condition like :

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);
$result = "";

foreach ($k as $l) 
{
    if( empty($result) ){
        echo $l."<br>";
        $result = $l;
    }else{
        $result .= '/'.$l;
        echo $result."<br>";
    }
} 

Or using the shortened version inside loop with ternary operation, like :

foreach ($k as $l) 
{
    $result .= empty($result) ? $l : '/'.$l;
    echo $result."<br>";
}

The output will be :

wordpress
wordpress/corporate
wordpress/corporate/business

Upvotes: 4

user1438038
user1438038

Reputation: 6059

How about constructing the results from the array alements:

$tara = 'wordpress/corporate/business';
$k = explode('/', $tara);

$s = '';
foreach ($k as $l) {
    $s .= ($s != '' ? '/' : '') . $l;
    var_dump($s);
}

This results in:

string(9) "wordpress"

string(19) "wordpress/corporate"

string(28) "wordpress/corporate/business"

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Create new array and inside foreach

<?php
$tara = 'wordpress/corporate/business';
$url = array();
foreach(explode("/",$tara) as $val){
  $url[] = $val;
  echo implode("/",$url)."\n";  
}
?>

Demo : https://eval.in/932527

Output is

wordpress
wordpress/corporate
wordpress/corporate/business

Upvotes: 0

Related Questions