Reputation: 83
I have two pages like this:
test.html
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="test2.php">
<textarea id="input" name="input" cols="100px" rows="15" wrap="soft" placeholder="put input here"></textarea>
<button type="button" onclick="getLength()">Get length </button><p id="length"> </p></div>
<br >
<input type="submit">
</form>
<script>
function getLength(){
var len=$('textarea').val().length;
$('#length').text(len);
}
</script>
</body>
</html>
And test2.php
<?php
echo strlen($_POST['input']);
?>
When I enter some input eg: "aa[pressEnter]aa"
, It should echo 5 at test2.php page but it echoes 6 instead.
So why it is 6 (what is extra character) ?
thanks for reading!
Upvotes: 0
Views: 281
Reputation: 746
Return is counted as an extra character in chrome.
Actually return is 2 escape characters \r\n. In chrome it takes one character (idk why), in edge it takes it as 2 characters so aa[enter]aa sums up to 6 characters
EDIT: 2 parts are there, one is js fix for removal of return carriage and one is php fix
js fix in html file
<!DOCTYPE html>
<head>
</head>
<body>
<form method="POST" action="test2.php">
<textarea id="input" name="input" cols="100px" rows="15" wrap="soft" placeholder="put input here"></textarea>
<button type="button" onclick="getLength()">Get length </button><p id="length"> </p></div>
<br >
<input type="submit">
</form>
<script>
function getLength(){
var fixedText = $('textarea').val();
fixedText = fixedText.replace(/(\r\n|\n|\r)/gm, "");
var len=fixedText.length;
$('#length').text(len);
}
</script>
</body>
</html>
php fix
<?php
$data = str_replace("\r\n",'',$_POST['input']);
echo strlen($data);
?>
You just need to replace the return carriages \r\n, \r and \n with "".
Upvotes: 1