Priince paul Gates
Priince paul Gates

Reputation: 1

Delete the word after 15 characters in PHP with white space support

I want to get the first 15 characters in this word with white space support.

$word = 'my word\n\nis this my word?\nMagnum\nwtwsetst.\nwtvet\n\n#rp';

should the result to be:

"my word

is thi..."

Upvotes: 0

Views: 53

Answers (2)

Manoj Yadav
Manoj Yadav

Reputation: 6612

You need to put string in " to escaped characters to work and use substr function, Try this:

$word = "my word\n\nis this my word?\nMagnum\nwtwsetst.\nwtvet\n\n#rp";
echo substr($word, 0, 15);

Demo Link

Upvotes: 1

Adrian
Adrian

Reputation: 1046

Use the substr() function.

$word = 'my word\n\nis this my word?\nMagnum\nwtwsetst.\nwtvet\n\n#rp';
echo substr(str_replace('\n', "\n", $word), 0, 15);

Although I see in one of your comments, you have said this doesn't preserve whitespace. It will, but you're not seeing it.

If you're echoing this within/to HTML, which I presume you are, and you're not in <pre> tags, try converting line-breaks \n to <br />.

So try,

$word = 'my word\n\nis this my word?\nMagnum\nwtwsetst.\nwtvet\n\n#rp';
echo nl2br(substr(str_replace('\n', "\n", $word), 0, 15));

Upvotes: 2

Related Questions