separate each words in php

时间:2017-10-12 10:04:57

标签: php codeigniter

I had an value in database like "demo text" . I want to display this content from the db in the view page as

demo text

Html code that i am using is like this <h2>Demo<span>Text</span></h2> , is there any solution for seperate each words and use one for h2 and other for span. I am using php codeigniter for the project , I don't know that whether the way i explained my problem is correct or not .

2 个答案:

答案 0 :(得分:3)

Yes you can so it with explode

if you have stored at least 2 words with space. try following

$demo ="demo text";
$arr = explode(" ",$demo);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;

DEMO

EDIT

If you have more words and want to split first word only you can pass limit parameter in explode

$demo ="Pligrimage to Marian Shrines";
$arr = explode(" ",$demo,2);
$str = "<h2>".$arr[0]."<span>".$arr[1]."</span></h2>";
echo $str;

DEMO

答案 1 :(得分:1)

我认为你正在寻找类似的东西!

$your_string = "Hello Houston! We have a problem!";
$my_array = explode(" ",trim($your_string));
$output = "<h2>";

foreach($my_array as $a_word){
    if ($a_word === reset($my_array))
        $output .= $a_word;
    else
        $output .= " <span>". $a_word . "</span>";
}

$output .= "</h2>";

print $output;