简体   繁体   中英

substr() in php doesn't index past '<' html tags

I am trying to do a very simple procedure.

I have a string:

$str = 'i am a div <div>hello</div>';

When i use substr to get a slice of the str:

echo substr($str,0,1) // i
echo substr($str,0,2) // i
echo substr($str,0,3) // i a
echo substr($str,0,4) // i am
echo substr($str,0,5) // i am
echo substr($str,0,6) // i am a
echo substr($str,0,7) // i am a
echo substr($str,0,8) // i am a <
echo substr($str,0,9) // i am a             <- what is going on here, lost the '<'?

I have noticed that substr doesn't find any character after the < literal. So from index 9 to the end it will always print i am a . Why is this and how can i get around this?

I want to get up to the > of the opening tag. so:

echo substr($str,0,15) // output => i am a div <div>

use this:

$str = htmlspecialchars('i am a div <div>hello</div>');

There is nothing wrong with substr(), it actually does the job, the reason why you can't see the result is because you are testing it out on the browser, when echoing the output inside the browser try to filter it first with echo htmlentities(substr($str,0,15)); .

I tried you code on the terminal and outputs the following

// phptest.php
<?php

$str = 'i am a div <div>hello</div>';


for ($i = 1; $i < strlen($str) + 1; $i++) {
    echo substr($str, 0, $i) . PHP_EOL;
}
# terminal
$ > php phptest.php
i
i
i a
i am
i am
i am a
i am a
i am a d
i am a di
i am a div
i am a div
i am a div <
i am a div <d
i am a div <di
i am a div <div
i am a div <div>
i am a div <div>h
i am a div <div>he
i am a div <div>hel
i am a div <div>hell
i am a div <div>hello
i am a div <div>hello<
i am a div <div>hello</
i am a div <div>hello</d
i am a div <div>hello</di
i am a div <div>hello</div
i am a div <div>hello</div>

see there's nothing wrong with substr(), it's in your browser, because it reads it as an invalid Html, that why all character starts from < doesn't render by the browser

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM