PHP: How should I convert this inconsistent string into arrays? - php

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().

Related

Is it possible to cut a word in parts? [PHP]

I would like to ask if it is possible to cut a word like
"Keyboard" in multiple strings, in PHP?
I want the string to be cut whenever a / is in it.
Example:
String: "Key/boa/rd"
Now I want that the cut result look like this:
String1: "Key"
String2: "boa"
String3: "rd"
You can use the PHP explode function. So, if your string was "Key/boa/rd", you would do:
explode('/', 'Key/boa/rd');
and get:
[
"Key",
"boa",
"rd",
]
It's unclear from your question, but if you don't want an array (and instead would like variables) you can use array destructuring like so:
[$firstPart, $secondPart, $thirdPart] = explode('/', 'Key/boa/rd');
However, if the string only had one / then that approach could lead to an exception being thrown.
The answer by Nathaniel assumes that your original string contains / characters. It is possible that you only used those in your example and you want to split the string into equal-length substrings. The function for that is str_split and it looks like:
$substrings = str_split($original, 3);
That will split the string $original into an array of strings, each of length 3 (except the very last one if it doesn't divide equally).
You can travel through the line character by character, checking for your delimeter.
<?php
$str = "Key/boa/rd";
$i = $j = 0;
while(true)
{
if(isset($str[$i])) {
$char = $str[$i++];
} else {
break;
}
if($char === '/') {
$j++;
} else {
if(!isset($result[$j])) {
$result[$j] = $char;
} else {
$result[$j] .= $char;
}
}
}
var_export($result);
Output:
array (
0 => 'Key',
1 => 'boa',
2 => 'rd',
)
However explode, preg_split or strtok are probably the goto Php functions when wanting to split strings.

how to store last character of the world from the string into an array in PHP

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
)

Count delimiter(s) of a string [duplicate]

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";

What is the most efficient way to count all the occurrences of a specific character in a PHP string?

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";

Most efficient way to delimit key

Say I have a string of 16 numeric characters (i.e. 0123456789012345) what is the most efficient way to delimit it into sets like : 0123-4567-8901-2345, in PHP?
Note: I am rewriting an existing system that is painfully slow.
Use str_split():
$string = '0123456789012345';
$sets = str_split($string, 4);
print_r($sets);
The output:
Array
(
[0] => 0123
[1] => 4567
[2] => 8901
[3] => 2345
)
Then of course to insert hyphens between the sets you just implode() them together:
echo implode('-', $sets); // echoes '0123-4567-8901-2345'
If you are looking for a more flexible approach (for e.g. phone numbers), try regular expressions:
preg_replace('/^(\d{4})(\d{4})(\d{4})(\d{4})$/', '\1-\2-\3-\4', '0123456789012345');
If you can't see, the first argument accepts four groups of four digits each. The second argument formats them, and the third argument is your input.
This is a bit more general:
<?php
// arr[string] = strChunk(string, length [, length [...]] );
function strChunk() {
$n = func_num_args();
$str = func_get_arg(0);
$ret = array();
if ($n >= 2) {
for($i=1, $offs=0; $i<$n; ++$i) {
$chars = abs( func_get_arg($i) );
$ret[] = substr($str, $offs, $chars);
$offs += $chars;
}
}
return $ret;
}
echo join('-', strChunk('0123456789012345', 4, 4, 4, 4) );
?>

Categories