How to get only operands with regex - php

I am trying to extract only operands viz. + - / and * from my arithmetic expression.
E.g.: A + B should return me +
I tried using following few RegEx but I always get an array with 3 elements:
Expression #1:
print_r (var_dump(preg_split ( "/([\w\s]*[^\-\+\/\*])/", "A+B" )), TRUE);
Output:
array(3) {
[0] =>
string(0) ""
[1] =>
string(1) "+"
[2] =>
string(0) ""
}
Expression #2:
print_r (var_dump(preg_split ( "/(?!\+|\-|\*|\/)[\w\s]+/", "A+B" )), TRUE);
Output:
array(3) {
[0] =>
string(0) ""
[1] =>
string(1) "+"
[2] =>
string(0) ""
}
I just want a + sign as output.
Any clue what am I doing wrong?

As Wiktor said you'd better use preg_match, but if you really want to use preg_split use the flag PREG_SPLIT_NO_EMPTY and simplify your regex:
print_r (var_dump(preg_split ( "/[\w\s]/", "A+B", -1, PREG_SPLIT_NO_EMPTY )), TRUE);
Output:
array(1) {
[0]=>
string(1) "+"
}

You can use preg_match_all :
preg_match_all ( "/([\^\-\+\/\*])/", "A+B", $result );
$result = $result[0];
print_r($result);
The result is :
Array ( [0] => + )

Related

PHP Why two same value from two different string are not equal to each other

Why are these two strings not equal?
I tried to get the same name so I can create a file, however I cannot get two strings equal to each other, even though I think both strings have the same value.
I uploaded var_dump output
any idea how to fix it?
$selectCategory = scandir($_SERVER['DOCUMENT_ROOT'].'/database/');
$cat = explode('.',$category);
print_r($cat);
print_r($selectCategory);
if($cat[0] == $selectCategory[2]){
echo " true";
}
else{
echo "no";
}
output:
Array ( [0] => bus [1] => php )
Array ( [0] => . [1] => .. [2] => bus [3] => fruit )
no
This is var_dump output
array(2) { [0]=> string(5) " bus" [1]=> string(3) "php" }
array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "bus" [3]=> string(5) "fruit" }
no
As you can see from the var_dump output the items you are comparing are different lengths. There is a space and possibly a hidden character in the $cat one:
To trim all space and some other characters use this:
$cat = array_map('trim', $cat);
$selectCategory = array_map('trim', $selectCategory);

How can I avoid a str_split error in php?

I'm trying to split a variable at every character, but I ran across this error:
Warning: str_split() expects parameter 2 to be long, string
The code is:
$split = str_split($num, "");
With $num being taken from the url, which only consist of numbers.
How can fix this?
The second parameter should be a number like this
<?php
$num = 100;
$split = str_split($num, 1);
print_r($split);
RESULT:
Array
(
[0] => 1
[1] => 0
[2] => 0
)
In fact you can leave the second parameter out if it is a 1 like this
<?php
$num = 100;
$split = str_split($num);
print_r($split);
And you will get the same result
As you said split a variable at every character you can just run
$split = str_split($num);
Make sure $num in not empty
Syntax str_split(string,length)
Example
<?php
print_r(str_split("1234"));
?>
Outputs - Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
You can use this:
$splitText = 1223;
$split = str_split((string) $splitText); //only on php 7
var_dump($split);
you will get this:
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "2"
[3]=>
string(1) "3"
}
Usage: array str_split ( string $string [, int $split_length = 1 ] ), but check the manual.

Simple array_diff not working

I have 2 arrays.
The first one is $teach_array and the second one is $langs_array.
Their respective values are:
$teach_array : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
$langs_array : Array ( [0] => 2 [1] => 3 )
Im trying to return a new array containing all the entries from $teach_array that are not present in $langs_array.
So the end result should be: Array ( [0] => 1 [3] => 4 [4] => 5 )
I have tried using a couple of methods including :
Option 1
$result = array_diff($teachArray, $language_1d_array);
This still returns all the values of $teach_array.
Option 2
$result = array_diff_key($teachArray, $language_1d_array);
However, this only returns Array ( [2] => 3 [3] => 4 [4] => 5 ) which is not correct.
Option 3
$result = array_values(array_diff_key($teachArray, $language_1d_array));
This returns the same result as Option 2. I also tried using only array_diff instead of array_diff_key and it returns the same result as Option 1.
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
hope you have already found the solution, but just in case I want to point you on following.
Blockquote
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
No single value from $teach_array matches any value of $lang_array.
Because there are differently formatted values, one array contains whitespaces before and after the value you want to match " 2 ".
var_dump($teach_array) => array(5) { [0]=> string(5) " 4 " ... }
var_dump($lang_array) => array(5) { [0]=> string(1) "2" ... }
I guess you have some whitespaces included. Please try again with:
$diff = array_diff(array_map('trim', $teach_array), $lang_array);
PHPTester just tested yours, works fine for me..?
$teachArray =[1,2,3,4,5];
$langsarray =[2,3];
$result = array_diff($teachArray,$langsarray);
print_r($result);
works and prints 1, 4, 5 for me.
BUT...here's a solution for what you're trying to acquire: the values in teacher array that are not in langs
$new_array = array();
foreach($teach_array as $item){ // Loop the teacher_array
if(!in_array($item,$langs_array)){ // If the teach_array value doesn't exist in the lang_array, add the value
$new_array[] = $item;
}
}
I'm sure theres a more elegant way, but this works:
$teach = [1, 2, 3,4, 5];
$langs = [2, 3];
$result = [];
foreach ($teach as $key => $t) {
if (!in_array($t, $langs)) {
$result[$key] = $t;
}
}
var_dump($result);
This is (basically) what you say you have. It works for me:
<?php
$fred = array(0=>1, 1=>2, 2=>3, 3=>4, 4=>5);
$bert = array(0=>2, 1=>3);
$res = array_diff($fred, $bert);
print_r($res);

PHP - Splitting string lines up into two variables

Not sure how I would do this but if someone could point me in the right track that'll be great, basically I've got a lone line of text in a variable which looks like this:
Lambo 1; Trabant 2; Car 3;
Then I want to split "Lambo" to it's own variable then "1" to it's own variable, and repeat for the others. How would I go and do this?
I know about explode() but not sure how I would do it to split the variable up twice etc.
As requested in the comments my desired output would be like this:
$Item = "Lambo"
$Quantity = 1
Then echo them out and go back to top of loop for example and do the same for the Trabant and Car
<?php
$in = "Lambo 1; Trabant 2; Car 3;";
foreach (explode(";", $in) as $element) {
$element = trim($element);
if (strpos($element, " ") !== false ) {
list($car, $number) = explode(" ", $element);
echo "car: $car, number: $number";
}
}
You can use explode to split the input on each ;, loop over the results and then split over each .
You can use preg_split and iterate over the array by moving twice.
$output = preg_split("/ (;|vs) /", $input);
You could use preg_match_all for getting those parts:
$line = "Lambo 1; Trabant 2; Car 3;";
preg_match_all("/[^ ;]+/", $line, $matches);
$matches = $matches[0];
With that sample data, the $matches array will look like this:
Array ( "Lambo", "1", "Trabant", "2", "Car", "3" )
$new_data="Lambo 1;Trabant 2;Car 3;" ;
$new_array=explode(";", $new_data);
foreach ($new_array as $key ) {
# code...
$final_data=explode(" ", $key);
if(isset($final_data[0])){ echo "<pre>".$final_data[0]."</pre>";}
if(isset($final_data[1])){echo "<pre>".$final_data[1]."</pre>";}
}
This places each word and number in a new key of the array if you need to acess them seperatly.
preg_match_all("/(\w+) (\d+);/", $input_lines, $output_array);
Click preg_match_all
http://www.phpliveregex.com/p/fM8
Use a global regular expression match:
<?php
$subject = 'Lambo 1; Trabant 2; Car 3;';
$pattern = '/((\w+)\s+(\d+);\s?)+/Uu';
preg_match_all($pattern, $subject, $tokens);
var_dump($tokens);
The output you get is:
array(4) {
[0] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[1] =>
array(3) {
[0] =>
string(8) "Lambo 1;"
[1] =>
string(10) "Trabant 2;"
[2] =>
string(6) "Car 3;"
}
[2] =>
array(3) {
[0] =>
string(5) "Lambo"
[1] =>
string(7) "Trabant"
[2] =>
string(3) "Car"
}
[3] =>
array(3) {
[0] =>
string(1) "1"
[1] =>
string(1) "2"
[2] =>
string(1) "3"
}
}
In there the elements 2 and 3 hold exactly the tokens you are looking for.

PHP spilt a 4 character string by character

I have string like so $string = 0730 I am looking to spilt this into an array like so:
$string[0] = 0
$string[1] = 7
$string[2] = 3
$string[3] = 0
I have looked into explode, but I do not have a delimiter or would just "" work?
Or is there another php function I should use?
You can just access the string as an array:
$string = "0730";
echo $string[1]; // 7
But if you need an array (for using in array_map or something), use str_split
use str_split() function
$string = '0730';
print_r(str_split($string));
output:
Array
(
[0] => 0
[1] => 7
[2] => 3
[3] => 0
)
You can use the str_split() function:
$string = "0730";
var_dump(str_split($string));
which gives you:
array(4) {
[0]=>
string(1) "0"
[1]=>
string(1) "7"
[2]=>
string(1) "3"
[3]=>
string(1) "0"
}

Categories