Hello guys, I'm new to programming especially in php.

i would like to know how to use the substr() in this kind of problem.

problem:
I have this string.
$stringA = "Hello to all of you!"

output should be this:
"Hello to ..."

I try to use the substr how to obtain this kind of output but i dont get it right.
Please help me.
I do appreciate all your Help.

Recommended Answers

All 4 Replies

Following code is ur ans.

substr($stringA,0,8) means it take 0-8 character including space.

<?php
$stringA = "Hello to all of you!";
echo substr($stringA,0,8)." "."...";
?>

commented: Thanks it help me +1

To explain the substr function the best is to look at it this way:

substr(STRING_YOU_ARE_LOOKING_IN, starting_position, how_many_chars_from_starting_position);
These positions are ordered numbers of the letters in the word.
Example:
word "Hello",
Letter H = 0
e = 1
l = 2
l = 3
o = 4

So, for example:

$search="Hello to all of you!";



echo substr($search,0,4); //this would print out "Hell"

//if you don't use the second number (how_many_chars_from_starting_position),
//program will automatically take the substring FROM the starting position till the //end of the word

//Example:

echo substr($search, 3); //Considering that letter with index number 3 (remember we are counting from 0 as a first letter) is letter "l", this would print out
"lo to all of you!".

Hope this was helpful to you,

Cheers,

Toni

commented: Thanks it helps me to understand this substr. +1
echo substr($search,0,4); //this would print out "Hello"

Not quite. That would print out "Hell" (4 characters)

commented: thank you +1

Not quite. That would print out "Hell" (4 characters)

Yup, my mistake, corrected it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.