I'm writing a plugin that needs to display text retrieved from another website (text as in lyrics) and the string I get from the query is displayed in a line, while I'd like to display it on multiple lines. When I enter the query address manually in my browser, I get a single line also, but when I display the source code, it's displayed on multiple lines.

Any idea on how I can achieve that? Here's my code so that you get an idea of what I mean:

public function get_lyrics($artist, $song){
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data= curl_exec($ch);
    return ($data);

and where it's called:

echo "Lyrics: ".$this->get_lyrics($artist, $song)."</div>";

I tried finding a similar question before asking, but as you might have noticed, I had a hard time describing my question precisely enough to make it specific and match any previous question. Sorry if it's been answered before :/

Anyways, thanks for your time! :)


EDIT 2: I come up with this kind of dirty solution, which is a function creating temporary array. It will contains the segment of the string you want to add line breaks to. Then we set it back as a string using implode.

function breakLines($str,$line_length=30,$implodechar='<br>')
    $str_length = strlen($str); 
    $tmp = array();//temporary array
    for ($j=0; $j<$str_length; $j++) 
        //if we are at the end of line and
        //that the current char is a space or punctuation char
        if($i>=$line_length && preg_match('/[\s\,\;\.\:]/isu', $str[$j]))
            //we update the offset              
            //we reset our counter

    return implode($implodechar,array_filter($tmp));

so you can use it simply like :

echo "Lyrics: ".breakLines($this->get_lyrics($artist, $song))."</div>";

Hope it helps :)

EDIT: oooops, sorry I understood the contrary of what you are trying to achieve.

How about using the preg_replace function with a pattern looking for line breaks ?

echo "Lyrics: ".preg_replace('/(\R+)?/isu', '',$this->get_lyrics($artist, $song))."</div>";

I added the lower "u" modifier for handling encoding.

You can test it here : http://www.phpliveregex.com/p/ns1#preg-replace

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.