0

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.

4
Contributors
4
Replies
5
Views
6 Years
Discussion Span
Last Post by tnjiric
1

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)." "."...";
?>

Votes + Comments
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

Edited by tnjiric: n/a

Votes + Comments
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)

Votes + Comments
thank you
1

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

Yup, my mistake, corrected it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.