am trying to remove duplicates values from Arabic string input but
`$input = "اللہ";
$step1 = preg_split("/(?<!^)(?!$)/u", $input);
$step2 = implode(' ',step1);
$step3 = array_unique(step2 );
echo "step3";`
i need output like this
ا ل ھ
Can you try this?
$input = "اللہ";
$step1 = preg_split("/(?<!^)(?!$)/u", $input);
$step2 = implode(' ',$step1);
$step3 = str_split($step2);
$step4 = array_unique($step3);
$result = implode('', $step4);
echo "$result";
Instead of running a regular expression, you could use the multibyte function mb_str_split() from the mb_string library. It is made to handle special charsets. Your PHP config might already enable it to replace usual PHP functions, but in this case you should check your INI file, or you can add some ini_set() calls at the beginning of your code. But the easiest is just to call the mb_* functions.
Secondly, as #CBroe pointed out, you made a few mistakes in your code by passing a string to a function that wants an array as parameter.
This is what you can do:
<?php
header('Content-Type: text/plain; charset=UTF-8');
$input = "اللہ";
$step1 = mb_str_split($input, 1, 'UTF-8');
print 'mb_str_split() returns ' . var_export($step1, true) . PHP_EOL;
$step2 = array_unique($step1);
print 'array_unique() returns ' . var_export($step2, true) . PHP_EOL;
print 'Desired output string is "' . implode(' ', $step2) . '"' . PHP_EOL;
Output:
mb_str_split() returns array (
0 => 'ا',
1 => 'ل',
2 => 'ل',
3 => 'ہ',
)
array_unique() returns array (
0 => 'ا',
1 => 'ل',
3 => 'ہ',
)
Desired output string is "ا ل ہ"
You can run it here: https://onlinephp.io/c/fe990
Related
Whith this code I'm trying to split a string in the "//" but it only gives me a value on the $splits[1] and on the $splits[0] gives me nothing.
while($row = $result->fetch_assoc()) {
$amigos[] = $row["Id2"]."//".$row["ID"];
}
foreach ($amigos as $i => $value) {
$splits = preg_split("//", $value);
$IDAmizade = $splits[0];
$IDAmigo = $splits[1];
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='$IDAmigo'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo($row["Nome"] . "+" . $row["Agrupamento"] . "+". $IDAmizade . "/");
}
And yes the $_row["Id2"] is returning a number i've confirm that.
The string that i'm trying to split is like: "1//3"
and after the split it gives me splits[0] is nothing and splits[1] is 3
what am I doing wrong?
The reason the 0 index is empty is because when using preg_split in this part preg_split("//", the first argument is the regex which uses / as a delimiter so you are splitting the string on an empty string.
$pattern = "//";
$string = "1//3";
print_r(preg_split($pattern, $string));
Output
Array
(
[0] =>
[1] => 1
[2] => /
[3] => /
[4] => 3
[5] =>
)
If you want to use preg_split with / as a delimiter and split on // you have to escape the forward slash.
$pattern = "/\/\//";
If you would use another delimiter like ~ the pattern would look like
$pattern = "~//~";
As already pointed out, you could use explode instead
$string = "1//3";
print_r(explode("//", $string));
Output
Array
(
[0] => 1
[1] => 3
)
You need to change your preg_split pattern. What you're doing at the moment will split the string up into its component characters.
So
$splits = preg_split("//", $value);
Should be:
$splits = preg_split("[//]", $value);
See more about preg_split here, and more about regular expressions here.
Alternatively, you could use explode, which splits a string by another string.
$splits = explode("//", $value);
As said in comment, why do you have 2 loops? A single one is enough and you don't need to split a string:
while($row = $result->fetch_assoc()) {
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='" . $row["ID"] . "'";
$result2 = $conn->query($sql);
$row2 = $result2->fetch_assoc();
echo($row2["Nome"] . "+" . $row2["Agrupamento"] . "+". $row["Id2"] . "/");
}
Moreover you'd better use a JOIN instead of doing a second SELECT in the loop. I can't say more because we don't know the schema of the database and what is the database.
I am attempting to define allowed characters in an array, and then sanitize strings based on this array. The below code works pretty good except that it removes chars 0-9 too!
Could someone please explain why this is?
Code:
<?php
//Allowed characters within user data:
$symbols = array();
$symbols += range('a', 'z');
$symbols += range('A', 'Z');
$symbols += range('0', '9');
array_push($symbols,' ','-'); // Allow spaces and hyphens.
//----test 1
//data to test.
$someString = "07mm04dd1776yyyy";
//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/i", "", $someString));
echo "$someString\n";
//----test 2
$someString = "Another-07/04/1776-test-!##$%^&*()[]\\;',./\"[]|;\"<>?";
//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/i", "", $someString));
echo "$someString\n";
?>
Output:
mmddyyyy
Another--test-
Sidenote (edit): This is used in conjunction with a database but it goes beyond the DB, the data in the DB is used to write powershell scripts which import users into Active Directory, and many characters are not allowed, plus the old system only allowed these characters also.
Thank you in advance,
Wayne
Going off of what #andrewsi said with the allowed chars not being added to the array, I figured out how to add them properly. The below code shows they are added, and the outputs of the test strings.
There's probably a better way to do this, so I added it to the community wiki.
<?php
//Allowed characters within user data:
$symbols = array();
array_push($symbols,implode("",range('0', '9')));
array_push($symbols,implode("",range('a', 'z')));
array_push($symbols,implode("",range('A', 'Z')));
array_push($symbols,' ','-'); // Allow spaces and hyphens.
print_r($symbols);
echo "\n";
//----test 1
//data to test.
$someString = "07mm04dd1776yyyy";
//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/", "", $someString));
echo "$someString\n";
//----test 2
$someString = "Another-07/04/1776-test-!##$%^&*()[]\\;',./\"[]|;\"<>?";
//sanatize
$someString = trim(preg_replace("/[^" . preg_quote(implode('',$symbols), '/') . "]/", "", $someString));
echo "$someString\n";
?>
Output:
Array
(
[0] => 0123456789
[1] => abcdefghijklmnopqrstuvwxyz
[2] => ABCDEFGHIJKLMNOPQRSTUVWXYZ
[3] =>
[4] => -
)
07mm04dd1776yyyy
Another-07041776-test-
I am trying to create an array from a plain text variable like so in php:
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
print_r( array($arraycontent) );
But it outputs the entire string as [0]
Array ( [0] => 'foo', 'bar', 'hallo', 'world' )
I would like 'foo' to be [0]
bar to be [1] and so on. Any pointers? Is this even possible?
YIKES, why are these all so long?
Here's a one liner:
explode("', '", trim($arraycontent, "'"));
If your string was like this:
$arraycontent = "foo, bar, hallo, world"
With only the commas separating, then you could use explode, like this:
$myArray = explode(", ", $arraycontent);
This will create an array of strings based on the separator you define, in this case ", ".
If you want to keep the string as is, you can use this:
$myArray = explode("', '", trim($arraycontent, "'"));
This will now use "', '" as the separator, and the trim() function removes the ' from the beginning and end of the string.
If this is PHP you could use:
$foo = "'foo', 'bar', 'hallo', 'world'";
function arrayFromString($string){
$sA = str_split($string); array_shift($sA); array_pop($sA);
return explode("', '", implode('', $sA));
}
print_r(arrayFromString($foo));
eval('$array = array('.$arraycontent.');');
Would be the shortest way.
$array = explode(',', $arraycontent);
$mytrim = function($string) { return trim($string, " '"); };
$array = array_map($mytrim, $array);
A safer and therefore better one. If you have different whitespace characters you would have to edit the $mytrim lambda-function.
Here is a variant that based on the input example would work, but there might be corner cases that is not handled as wanted.
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$arrayparts = explode(',', $arraycontent); // split to "'foo'", " 'bar'", " 'hallo'", " 'world'"
for each ($arrayparts as $k => $v) $arrayparts[$k] = trim($v, " '"); // remove single qoute and spaces in beggning and end.
print_r( $arrayparts ); // Array ( [0] => 'foo', [1] => 'bar', [2] => 'hallo', [3] => 'world' )
This should give what you want, but also note that for example
$arraycontent = " ' foo ' , ' bar ' ' ' ' ', 'hallo', 'world'";
Would give the same output, so the question then becomes how strict are the $arraycontentinput?
If you have to have input like this, I suggest trimming it and using preg_split().
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$trimmed = trim($arraycontent, " \t\n\r\0\x0B'\""); // Trim whitespaces and " and '
$result = preg_split("#['\"]\s*,\s*['\"]#", $trimmed); // Split that string with regex!
print_r($result); // Yeah, baby!
EDIT: Also I might add that my solution is significantly faster (and more universal) than the others'.
That universality resides in:
It can recognize both " and ' as correct quotes and
It ignores the extra spaces before, in and after quoted text; not inside of it.
Seems you are having problem while creating an array..
try using
<?php
$arraycontent = array('foo', 'bar', 'hallo', 'world');
print_r( array($arraycontent) );
?>
its output will be:
Array ( [0] => Array ( [0] => foo [1] => bar [2] => hallo [3] => world
) )
I'm looking around for a RegEx that can help me parse an nquad file. An nquad file is a straight text file where each line represents a quad (s, p, o, c):
<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext> .
<http://mysubject> <http://mypredicate2> <http://myobject2> <http://mycontext> .
<http://mysubject> <http://mypredicate2> <http://myobject2> <http://mycontext> .
The objects can also be literals (instead of uris), in which case they are enclosed with double quotes:
<http://mysubject> <http://mypredicate> "My object" <http://mycontext> .
I'm looking for a regex that given one line of this file, which will give me back a php array in the following format:
[0] => "http://mysubject"
[1] => "http://mypredicate"
[2] => "http://myobject"
[3] => "http://mycontext"
...or in the case where the double quotes are used for the object:
[0] => "http://mysubject"
[1] => "http://mypredicate"
[2] => "My Object"
[3] => "http://mycontext"
One final thing - in an ideal world, the regex will cater for the scenario there may be 1 or more spaces between the various components, e.g.
<http://mysubject> <http://mypredicate> "My object" <http://mycontext> .
I'm going to add another answer as an additional solution using only a regex and explode:
$line = "<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext>";
$line2 = '<http://mysubject> <http://mypredicate> "My object" <http://mycontext>';
$delimeter = '---'; // Can't use space
$result = preg_replace('/<([^>]*)>\s+<([^>]*)>\s+(?:["<]){1}([^">]*)(?:[">]){1}\s+<([^>]*)>/i', '$1' . $delimeter . '$2' . $delimeter . '$3' . $delimeter . '$4', $line);
$array = explode( $delimeter, $result);
It seems this can be accomplished as follows (I do not know your character restrictions so it may not work specifically for your needs, but worked for your test cases):
$line = "<http://mysubject> <http://mypredicate> <http://myobject> <http://mycontext>";
$line2 = '<http://mysubject> <http://mypredicate> "My object" <http://mycontext>';
// Remove unnecessary whitespace between entries (change $line to $line2 for testing)
$delimeter = '---';
$result = preg_replace('/([">]){1}\s+(["<]){1}/i', '$1' . $delimeter . '$2', $line);
// Explode on our delimeter
$array = explode( $delimeter, $result);
foreach( $array as &$a)
{
// Replace the characters we don't want with nothing
$a = str_replace( array( '<', '.', '>', '"'), '', $a);
}
var_dump( $array);
This regular expression would help:
/(\S+?)\s+(\S+?)\s+(\S+?)\s+(\S+?)\s+\./
(s, p, o, c) values will be in $1, $2, $3, $4 variables.
I want to concatenate one element of a multidimensional array with some strings.
<?
$string1 = 'dog';
$string2 = array
(
'farm' => array('big'=>'cow', 'small'=>'duck'),
'jungle' => array('big'=>'bear', 'small'=>'fox')
);
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>
By using this syntax for $string, I get:
dog Array[big] cat
I would like not to use the alternate syntax
$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;
which works.
What's wrong with "$string1 $string2[$type][$size] $string3"?
Use the "complex syntax":
$string = "$string1 {$string2[$type][$size]} $string3";
PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.
See PHP - Variable parsing.
I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:
$string = implode(' ', array($string1, $string2[$type][$size], $string3));
Use this:
$string = "$string1 {$string2[$type][$size]} $string3";