I have a question about the PHP trim function.
Consider the following:
$x= '<p>blah</p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This works as expected and prints blah
.
$x= '<p><b>blah</b></p>';
$x= trim(trim($x, '<p>'), '</p>');
echo htmlentities($x) . "<br />";
This prints b>blah</b
I'm not looking for other ways around this.
I do wonder why the trim function shows this behavior (stripping the extra Less-than/Greater-than sign).
Thanks in advance.
trim treats the 2nd argument as a list of characters that can be removed, not as a continuous string. This explains why b remains, but < and > are removed.
This is a default behaviour of trim function. You expect it to trim the exact string, but second parameter is instead a list of characters and any of them will be trimmed if found at each side of the string.
You could use simple RegEx like this:
$x = preg_replace(array('#^<p>#i', '#</p>$#i'), '', $x);
Related
I have a question about a String i want to count all the characters in the string. Like if i have a string
"Hello world & good morning. The date is 18.05.2016"
You can use explode() to convert string into array and then use count() function to count length of array.
echo count(explode(' ', "Hello world & good morning. The date is 18.05.2016"))
You can try this code.
<?php
$file = "C:\Users\singh\Desktop\Talkative Challenge\base_example.txt";
$document = file_get_contents($file);
$return_array = preg_split("/[\s,]+/",$document);
echo count($return_array);
echo $document;
?>
Hopefully it will be working fine.
The 3rd parameter of str_word_count allows you to set additional characters to be counted as words:
str_word_count($document, 0, '&.0..9');
&.0..9 means it will consider &, ., and range from 0 to 9.
You can count the spaces with substr_count and add one.
echo substr_count($str, " ")+1;
// 9
https://3v4l.org/oJJkt
I have a string which comprises of the words the user input in it so I don't know how many words will be there and what will be the index of each word so that I can find substring out of this. Can anyone tell me how to echo it without using or converting it into array and add next line whenever there is space in string. I am newbie to php. I checked for split method, explode method, all inbuilt methods are converting it into array which i dont need.
$var= "This is a sample code."
I want output like this:
This
is
a
sample
code
I tried this but it didnt work for me.
$count= str_word_count($var);
echo "$count";
$strlen= strlen($var);
for($i=0; $i<(int)$strlen;$i++ ){
if($var contains " "){
echo "\n";
}else {
echo $var;
}
}
I would appreciate your help. Thank you.
Use str_replace()
echo str_replace(" ", "\n", $var);
but you also can perform regular expression, that can give you maybe a better answer, it will be able to check only words, ignoring multiple spaces or other space characters.
$var= "This is a sample code.";
if ( preg_match_all("/(\w+)/si", $var, $m ) ){
echo implode("\n", $m[1]);
}
Without other builtin functions and just using for loop , This will give the expected output
for($i=0; $i<(int)$strlen;$i++ ){
if($var[$i]==" "){
echo "<br>";
}else if($var[$i] !='.'){
echo $var[$i];
}
}
I have line as 'Delux Room_room'. I want get 'Delux Room' as result. I tried following codes.
Following code give following result.
echo $row.'<br/>';
echo rtrim($row, 'room') .'<br/>';
echo rtrim($row, '_room') .'<br/>';
Result ;-
Delux Room_room
Delux Room_
Delux R
But i want Delux Room. Please help me.
echo rtrim($row, '_room') .'<br/>';
That says "remove characters from the end of the string until you get to one that isn't _, r, o or m." Which obviously isn't what you mean. From the PHP manual:
$charlist You can also specify the characters you want to strip, by means of the charlist parameter. Simply list all characters that you want to be stripped. With .. you can specify a range of characters.
You provide a list of characters, not a string you want to remove.
You should probably use substr instead:
echo substr($row, 0, -5); // remove the last 5 characers
Another solution would be to use str_replace to replace unwanted substrings:
echo str_replace('_room', '', $row); // replace "_room" with an empty string
Note that this is less precise than the substr approach.
rtrim's second argument is a set of characters. You'll have to write your own method to remove a specific string instead:
function rtrim_str($str, $trim) {
if (substr($str, -strlen($trim)) == $trim) {
return substr($str, 0, -strlen($trim));
}
return $str; // String not present at end
}
echo rtrim_str($row, '_room');
Alternatively to #lonesomeday's solution, if your last past is of variable length:
$pos = strrpos($row, '_');
echo $substr($row, 0, $pos);
You should use str_replace instead of rtrim, like this:
echo $row.'<br/>';
echo str_replace('room', '', $row) .'<br/>';
echo str_replace('_room', '', $row) .'<br/>';
OK, so there is a page I'm querying on another server that returns a comma separated list of two values. Something it would return would be:
850,640
I have some PHP code that calls file_get_contents on that page and needs to do some numeric calculations based on the two values.
No matter what I try, I can't seem to get an int value out of this.
$res = trim(file_get_contents('http://thatURL/'));
echo "X" . $res . "X<br/>";
list($x,$y) = array_map(create_function('$a', 'return (int)$a;'), explode(',', $res));
echo "X:$x";
results in the output:
X 850,640 X
X:0
Note the spaces before and after the comma separated values(how the hell? I trim'd them!) and that $x is assigned the value 0.
What am I doing wrong here?
What am I doing wrong here?
Nothing, as far as I can see, which indicates that the content of $res is not quite what you expect. Could you change the first echo to:
echo htmlentities($res);
My guess is $res contains some un-printed characters, for example, it is actually:
<span> </span>850,640<span> </span>
or
850,640
Try the following. The array_map and llamda function are arguably overkill for your usage.
$res = " 850,640 ";
echo "X" . $res . "X<br/>";
list($x,$y) = explode(',', trim($res));
echo "X:" . (int)$x;
echo "Y:" . (int)$y;
Worked for me, but I'm not using file_get_contents(). If that doesn't work, something else is being output by the page.
PHP is not a typed language. Use intval to convert a string to integer.
Correction: it is a loosely typed language! That's what I meant!
Since I was using file_get_contents() on a URL, there was some HTML being put in as well that I didn't notice in my echo because it parsed out... just empty body and html tags. Oops!
I need to get the last character of a string.
Say I have "testers" as input string and I want the result to be "s". how can I do that in PHP?
substr("testers", -1); // returns "s"
Or, for multibyte strings :
mb_substr("multibyte string…", -1); // returns "…"
substr($string, -1)
Or by direct string access:
$string[strlen($string)-1];
Note that this doesn't work for multibyte strings. If you need to work with multibyte string, consider using the mb_* string family of functions.
As of PHP 7.1.0 negative numeric indices are also supported, e.g just $string[-1];
From PHP 7.1 you can do this (Accepted rfc for negative string offsets):
<?php
$silly = 'Mary had a little lamb';
echo $silly[-20];
echo $silly{-6};
echo $silly[-3];
echo $silly[-15];
echo $silly[-13];
echo $silly[-1];
echo $silly[-4];
echo $silly{-10};
echo $silly[-4];
echo $silly[-8];
echo $silly{3}; // <-- this will be deprecated in PHP 7.4
die();
I'll let you guess the output.
Also, I added this to xenonite's performance code with these results:
substr() took 7.0334868431091seconds
array access took 2.3111131191254seconds
Direct string access (negative string offsets) took 1.7971360683441seconds
As of PHP 7.1.0, negative string offsets are also supported.
So, if you keep up with the times, you can access the last character in the string like this:
$str[-1]
DEMO
At the request of a #mickmackusa, I supplement my answer with possible ways of application:
<?php
$str='abcdef';
var_dump($str[-2]); // => string(1) "e"
$str[-3]='.';
var_dump($str); // => string(6) "abc.ef"
var_dump(isset($str[-4])); // => bool(true)
var_dump(isset($str[-10])); // => bool(false)
I can't leave comments, but in regard to FastTrack's answer, also remember that the line ending may be only single character. I would suggest
substr(trim($string), -1)
EDIT: My code below was edited by someone, making it not do what I indicated. I have restored my original code and changed the wording to make it more clear.
trim (or rtrim) will remove all whitespace, so if you do need to check for a space, tab, or other whitespace, manually replace the various line endings first:
$order = array("\r\n", "\n", "\r");
$string = str_replace($order, '', $string);
$lastchar = substr($string, -1);
I'd advise to go for Gordon's solution as it is more performant than substr():
<?php
$string = 'abcdef';
$repetitions = 10000000;
echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = substr($string, -1);
echo "substr() took " . (microtime(true) - $start) . "seconds\n";
$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
$x = $string[strlen($string)-1];
echo "array access took " . (microtime(true) - $start) . "seconds\n";
die();
outputs something like
----------------------------------
10000000 repetitions...
----------------------------------
substr() took 2.0285921096802seconds
array access took 1.7474739551544seconds
As of PHP 8 you can now use str_ends_with()
$string = 'testers';
if (\str_ends_with($string, 's') {
// yes
}
Remember, if you have a string which was read as a line from a text file using the fgets() function, you need to use substr($string, -3, 1) so that you get the actual character and not part of the CRLF (Carriage Return Line Feed).
I don't think the person who asked the question needed this, but for me, I was having trouble getting that last character from a string from a text file so I'm sure others will come across similar problems.
You can find last character using php many ways like substr() and mb_substr().
If you’re using multibyte character encodings like UTF-8, use mb_substr instead of substr
Here i can show you both example:
<?php
echo substr("testers", -1);
echo mb_substr("testers", -1);
?>
LIVE DEMO
A string in different languages including C sharp and PHP is also considered an array of characters.
Knowing that in theory array operations should be faster than string ones you could do,
$foo = "bar";
$lastChar = strlen($foo) -1;
echo $foo[$lastChar];
$firstChar = 0;
echo $foo[$firstChar];
However, standard array functions like
count();
will not work on a string.
Use substr() with a negative number for the 2nd argument.$newstring = substr($string1, -1);
Siemano, get only php files from selected directory:
$dir = '/home/zetdoa/ftp/domeny/MY_DOMAIN/projekty/project';
$files = scandir($dir, 1);
foreach($files as $file){
$n = substr($file, -3);
if($n == 'php'){
echo $file.'<br />';
}
}