Page 1 of 1
substr() - Problem !!
Posted: Mon Aug 15, 2011 4:20 am
by amirbwb
hello,
I want to use substr function to post first 500 letters from an article, here's my problem:
check this code
$a='<p>test devnetwork</p>';
$b=substr($a,0,5);
echo $b;
this will display me :
te
but actually the page code will be:
<p>te
the P:paragraph has open and didn't close ...
PS: I am going to use other than <p>, example <img src="test.jpg"> <div> <a href="test.php">
thank you,
Re: substr() - Problem !!
Posted: Mon Aug 15, 2011 6:36 am
by phphelpme
Hi there,
The issue you have here is you are echoing html code so your browser will execute that code:
Code: Select all
$a='<p>test devnetwork</p>';
$b=substr($a,0,5);
echo $b;
The correct answer would be: te as your browser is echoing the <p> portion and starting a paragraph.
Checkout your source code when you are viewing this example in your browser and you will see this: <p>te
You need to tell it to strip the html code or at least ignore them from the count. If you need the html code to be executed along with the content then ignore the html code using a function called strip_tags()
http://php.net/manual/en/function.strip-tags.php
Hope this helps you out.
Best wishes
Re: substr() - Problem !!
Posted: Mon Aug 15, 2011 10:52 am
by Odai_GH
hi
do it like this :
Code: Select all
$a='test devnetwork';
$b=substr($a,0,5);
echo "<p>".$b."</p>;

Re: substr() - Problem !!
Posted: Mon Aug 15, 2011 8:37 pm
by califdon
Odai_GH wrote:hi
do it like this :
Code: Select all
$a='test devnetwork';
$b=substr($a,0,5);
echo "<p>".$b."</p>;

No, that's wrong. Use phphelpme's solution.
Re: substr() - Problem !!
Posted: Tue Aug 16, 2011 4:19 am
by phphelpme
Odai_GH wrote:hi
do it like this :
Code: Select all
$a='test devnetwork';
$b=substr($a,0,5);
echo "<p>".$b."</p>;

This will produce only the same execution because all you have done is add the echo <p></p> so the output will be this: <p><p>te</p> and on the page you will see displayed te just the same. You are not dealing with the html code that is embedded into the paragraph to which the content is being taken.
For example:
Code: Select all
<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>
This will output:
Test paragraph. Other text
The syntax would be:
Code: Select all
<p>Test paragraph.</p> <a href="#fragment">Other text</a>
As you can see some html tags have been removed from the string value.
Best wishes
Re: substr() - Problem !!
Posted: Tue Aug 16, 2011 4:48 am
by amirbwb
I think that strip_tags() could help ... thank you all =)