What is the most efficient way to count all the occurrences of a specific character in a PHP string?
use this:
echo substr_count("abca", "a"); // will echo 2
Can you not feed the character to preg_match_all?
Not sure what kind of a response you're looking for, but here's a function that might do it:
function findChar($c, $str) {
indexes = array();
for($i=0; $i<strlen($str); $i++) {
if ($str{$i}==$c) $indexes[] = $i;
}
return $indexes;
}
Pass it the character you're looking for and the string you want to look:
$mystring = "She shells out C# code on the sea shore";
$mychar = "s";
$myindexes = $findChar($mychar, $mystring);
print_r($myindexes);
It should give you something like
Array (
[0] => 0
[1] => 4
[2] => 9
[3] => 31
[4] => 35
)
or something...
If you are going to be repeatedly checking the same string, it'd be smart to have some sort of trie or even assoc array for it otherwise, the straightforward way to do it is...
for($i = 0; $i < strlen($s); $i++)
if($s[i] == $c)
echo "{$s[i]} at position $i";
Related
I have a string like -
$str = "Hello how are you";
and i want to store last character in an array then the result look like below-
array(0=>o,1=>w,2=>e,3=>u)
how It can be achieve without the using of php explode(), substr() and array_split() methods.
This works without any function calls whatsoever (isset is actually a language construct, not a function.)
:
$str = "Hello how are you";
for ($i = 0; isset($str[$i]); $i++) {
if (!isset($str[$i + 1]) || $str[$i + 1] == " ") {
$result[] = $str[$i];
}
}
It addresses each byte of the string one at a time, checking to see if it's the last one or is followed by a space and adding it to the array if so. It's a simplistic set of rules for determining the end of a word, but illustrates the idea.
Verifying with print_r($result) outputs:
Array
(
[0] => o
[1] => w
[2] => e
[3] => u
)
i dunno why am i doing this but get it
$str = "Hello how are you";
$last='';
$i=0;
$result=array();
while ($i<strlen($str)){
if ($str[$i]==' '){
$result[]=$last;
}
$last= $str[$i];
if ($i==(strlen($str)-1)){
$result[]=$last;
}
$i++;
}
print_r($result);
The alternative solution using str_word_count function:
$str = "Hello how are you";
$last_chars = [];
foreach (str_word_count($str, 1) as $word) {
$last_chars[] = $word[strlen($word) - 1];
}
print_r($last_chars);
The output:
Array
(
[0] => o
[1] => w
[2] => e
[3] => u
)
As you mention you don't want to use explode, substr and split, so for now you need to use strlen for getting the string length.
After getting the array length you need to loop through the length and check if the character is a blank space or last character. If then add the previous character to the array of output.
$str = "Hello how are you";
$length = strlen($str);
$out = array();
for($i = 0; $i < $length; $i++){
if($str[$i] == " " || ($i == $length - 1)){
$out[] = $str[$i-1];
}
}
print_r($out);
Result
Array
(
[0] => o
[1] => w
[2] => e
[3] => u
)
I have a PHP generator which generates some $key => $value.
Is there an "easy" way to implode the values (by passing the generator name)? Or to transform it to an array?
I can do this with a couple of lines of code, but are there some builtins functions to accomplish this?
You can use iterator_to_array function for the same, have a look on below example:
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}
$generator = gen_one_to_three();
$array = iterator_to_array($generator);
print_r($array);
Output
Array
(
[0] => 1
[1] => 2
[2] => 3
)
One has to keep in mind that
A generator is simply a function that returns an iterator.
For instance:
function digits() {
for ($i = 0; $i < 10; $i++) {
yield $i;
}
}
digits is a generator, digits() is an iterator.
Hence one should search for "iterator to array" functions, to find iterator_to_array (suggested by Chetan Ameta )
i am receiving the name from the $request in php.I want to do something like to add all the letters of the name in the array during the request e.g
$name=$_request['name'];
say $name='test';
i want to save it in an array in this format as array("t","e","s","t").
how can i do it ?
str_split is your friend.
$split_string = str_split($name);
It may be sufficient for you to access the string directly as an array, without the need to format the data:
$a = 'abcde';
echo $a[2];
Will output
c
However you won't be able to perform some array operations, such as foreach
see the php site
so it would be like
$name= 'test';
$arr1 = str_split($name);
would result in a array like:
Array
(
[0] => t
[1] => e
[2] => s
[3] => t
)
Here you go
$i = 0;
while(isset($name[$i])) {
$nameArray[$i] = $name[$i];
$i++;
}
Try this:
$letters = array();
for (int $i=0; $i < strlen($name); $i++){
$letters[] = $name[$i];
}
and you can access it with:
for (int $i=0; $i < strlen($letters); $i++){
$letters[$i];
}
I have this string: $delims = ',^.;:\t' (which is used in a preg_replace() call).
I need two arrays .. one with those delimiters as the index ($delimCount), and another with those delimiters as the values ($delimiters).
The former will get values assigned from within a loop on the latter .. as such:
foreach ($delimiters as $delim) {
if( strpos($char, $delim) !== false) { // if the char is the delim ...
$delimCount[$delim]++; // ... increment
}
}
The way I have it now is messy, and I'd like to simply break that string into the two arrays ... but I'm getting tripped up on the \t delimiter (because it's the only one with two characters).
How can/should I handle that?
How I would handle your \t delimiter
$delims = ',^.;:\t';
$i = 0;
while($i < strlen($delims)) {
if($delims[$i] == chr(92)) {
$delimiters[] = $delims[$i] . $delims[$i+1];
$i = $i + 2;
}
else {
$delimiters[] = $delims[$i];
$i++;
}
}
Output of $delimiters
Array
(
[0] => ,
[1] => ^
[2] => .
[3] => ;
[4] => :
[5] => \t
)
As far as an array with the delimiters as an index
foreach($delimiters as $key=>$val) {
$delimCount[$val] = $val;
}
Output of $delimCount
Array
(
[,] => ,
[^] => ^
[.] => .
[;] => ;
[:] => :
[\t] => \t
)
Hope this helps.
I need two arrays .. one with those delimiters as the index ($delimCount), and another with those delimiters as the values ($delimiters).
Well, where does $delimiters come from? Did you write it yourself? If so, I'd argue you'd be better off making $delimiters an array in any case, and using implode when you use it in preg_replace.
If you have a problem with tabulator, then you can use ordinal number of character as the key inplace of character itself: $delim = "\t"; $delimCount[ ord($delim) ]++;
Handy complementary functions: ord() and chr().
What is the most efficient way to count all the occurrences of a specific character in a PHP string?
use this:
echo substr_count("abca", "a"); // will echo 2
Can you not feed the character to preg_match_all?
Not sure what kind of a response you're looking for, but here's a function that might do it:
function findChar($c, $str) {
indexes = array();
for($i=0; $i<strlen($str); $i++) {
if ($str{$i}==$c) $indexes[] = $i;
}
return $indexes;
}
Pass it the character you're looking for and the string you want to look:
$mystring = "She shells out C# code on the sea shore";
$mychar = "s";
$myindexes = $findChar($mychar, $mystring);
print_r($myindexes);
It should give you something like
Array (
[0] => 0
[1] => 4
[2] => 9
[3] => 31
[4] => 35
)
or something...
If you are going to be repeatedly checking the same string, it'd be smart to have some sort of trie or even assoc array for it otherwise, the straightforward way to do it is...
for($i = 0; $i < strlen($s); $i++)
if($s[i] == $c)
echo "{$s[i]} at position $i";