My array looks like:
{flower},{animals},{food},{people},{trees}
I want to explode with {, , & }.
My output should contain only words inside curly brackets.
My code:
$array = explode("},{", $list);
After execution of this code $array will be
$array = Array (
[0] => {flower
[1] => animals
[2] => food
[3] => people
[4] => trees}
)
But output array should be:
$array = Array (
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
Can anyone please tell me how can I modify my code to get this array?
I would go for preg_split like below
<?php
$list = "{flower},{animals},{food},{people},{trees}";
$array = preg_split('/[},{]/', $list, 0, PREG_SPLIT_NO_EMPTY);
print_r($array);
?>
The output is
Array
(
[0] => flower
[1] => animals
[2] => food
[3] => people
[4] => trees
)
You could try to extract the words using a RegEx instead of splitting the string:
$list = "{flower},{animals},{food},{people},{trees}";
// Match anything between curly brackets
// The "U" flag prevents the regex to make a single match with the first and last brackets
preg_match_all('~{(.+)}~U', $list, $result);
// Only keep the 1st capturing group
$words = $result[1];
var_dump($words);
Output:
array(5) {
[0]=>
string(6) "flower"
[1]=>
string(7) "animals"
[2]=>
string(4) "food"
[3]=>
string(6) "people"
[4]=>
string(5) "trees"
}
Related
Hello I have this string
$chineseString = "号码:91"
What I want to do is to explode() it and get a result like this:
array:2[
[0] => "号码",
[1] => "91"
]
The reason explode() didn't work for you is that your chineseString variable contains what is called in unicode a FULLWIDTH COLON (U+FF1A) and you are trying to split by a different character, a COLON (U+003A). So, if you use the correct character it will work.
$chineseString = "号码:91";
print_r(explode(":", $chineseString ));
Outputs: Array([0] => 号码, [1] => 91)
Take a look at this http://codepad.org/yYO3nljF
<?php
$chineseString = "号码:91";
$d = explode(":",$chineseString );
var_dump($d);
?>
output
array(2) {
[0]=>
string(6) "号码"
[1]=>
string(2) "91"
}
This seems to work for me:
$chineseString = "号码:91";
print_r(preg_split('/:/', $chineseString));
Results in: Array ( [0] => 号码 [1] => 91 )
I have a dialogue file that looks like so:
CHARACTER MOOD PROMPT RESPONSE TEXT LEVEL PATH
As you can see, everything is separated by spaces. The trick comes in when
PROMPT RESPONSE TEXT is supposed to be one header (read together) all heading groups are separated by no more than two spaces while each heading is separated by 3+ spaces. What I am trying to do is take this line and add it into an array much like this:
array(4) => {
[0]=> string(9) "CHARACTER",
[1]=> string(4) "MOOD",
[2]=> string(21) "PROMPT RESPONSE TEXT",
[3]=> string(5) "LEVEL",
[4]=> string(4) "PATH"
}
I am trying to use preg_split with the following regexp /\s\s\s+/ but it does nothing more than yield an empty array. I assume that the regexp would split if on any amount of spaces equal to or greater than 3. Is there something more to this?
You can use the following, this looks for whitespace ( at least 3 times )
$results = preg_split('/\s{3,}/', $text);
var_dump($results);
Output
array(5) {
[0]=> string(9) "CHARACTER"
[1]=> string(4) "MOOD"
[2]=> string(21) "PROMPT RESPONSE TEXT"
[3]=> string(5) "LEVEL"
[4]=> string(4) "PATH"
}
If you dont want to have the overhead of loading the regex engine you could use this
<?php
$t = 'CHARACTER MOOD PROMPT RESPONSE TEXT LEVEL PATH';
$u = explode(' ',$t);
print_r($u);
$new_u = array();
foreach( $u as $key => $val) {
if ($val != '') {
$new_u[] = trim($val);
}
}
print_r($new_u);
Results
Array
(
[0] => CHARACTER
[1] =>
[2] => MOOD
[3] =>
[4] =>
[5] => PROMPT RESPONSE TEXT
[6] =>
[7] => LEVEL
[8] =>
[9] =>
[10] => PATH
)
Array
(
[0] => CHARACTER
[1] => MOOD
[2] => PROMPT RESPONSE TEXT
[3] => LEVEL
[4] => PATH
)
The answer on this question, pointed me in a possible direction, but it processes the string once, then loops through the result. Is there a way to do it in one process?
My string is like this, but much longer:
954_adhesives
7_air fresheners
25_albums
236_stuffed_animial
819_antenna toppers
69_appliances
47_aprons
28_armbands
I'd like to split it on linebreaks, then on underscore so that the number before the underscore is the key and the phrase after the underscore is the value.
Just use a regular expression and array_combine:
preg_match_all('/^([0-9]+)_(.*)$/m', $input, $matches);
$result = array_combine($matches[1], array_map('trim', $matches[2]));
Sample output:
array(8) {
[954]=>
string(9) "adhesives"
[7]=>
string(14) "air fresheners"
[25]=>
string(6) "albums"
[236]=>
string(15) "stuffed_animial"
[819]=>
string(15) "antenna toppers"
[69]=>
string(10) "appliances"
[47]=>
string(6) "aprons"
[28]=>
string(8) "armbands"
}
Use ksort or arsort if you need the result sorted as well, by keys or values respectively.
You can do it in one line:
$result = preg_split('_|\n',$string);
Here is a handy-dandy tester: http://www.fullonrobotchubby.co.uk/random/preg_tester/preg_tester.php
EDIT:
For posterity, here's my solution. However, #Niels Keurentjes answer is more appropriate, as it matches a number at the beginning.
If you wanted to do this with regular expressions, you could do something like:
preg_match_all("/^(.*?)_(.*)$/m", $content, $matches);
Should do the trick.
If you want the result to be a nested array like this;
Array
(
[0] => Array
(
[0] => 954
[1] => adhesives
)
[1] => Array
(
[0] => 7
[1] => air fresheners
)
[2] => Array
(
[0] => 25
[1] => albums
)
)
then you could use an array_map eg;
$str =
"954_adhesives
7_air fresheners
25_albums";
$arr = array_map(
function($s) {return explode('_', $s);},
explode("\n", $str)
);
print_r($arr);
I've just used the first three lines of your string for brevity but the same function works ok on the whole string.
I have this sample string in a source:
#include_plugin:PluginName param1=value1 param2=value2#
What I want is to find all occurances of #include_plugin:*# from a source with a result of the PluginName and each paramN=valueN.
At this moment I'm fiddling with something like this (and have tried many variants): /#include_plugin:(.*\b){1}(.*\=.*){0,}#/ (using this resource). Unfortunately I can't seem to define a pattern which is giving me the result I want. Any suggestions?
Update with example:
Say I have this string in a .tpl-file. #include_plugin:BestSellers limit=5 fromCategory=123#
I want it to return an array with:
0 => BestSellers,
1 => limit=5 fromCategory=123
Or even better (if possible):
0 => BestSellers,
1 => limit=5,
2 => fromCategory=123
You can do it in 2 steps. First capture the line with a regex, then explode the parameters into an array:
$subject = '#include_plugin:PluginName param1=value1 param2=value2#';
$pattern = '/#include_plugin:([a-z]+)( .*)?#/i';
preg_match($pattern, $subject, $matches);
$pluginName = $matches[1];
$pluginParams = isset($matches[2])?explode(' ', trim($matches[2])):array();
You can use this regex:
/#include_plugin:([a-zA-Z0-9]+)(.*?)#/
The PluginName is in the first capturing group, and the parameters are in the second capturing group. Note that the parameters, if any, has a leading spaces.
It is not possible to write a regex to extract to your even better case, unless the maximum number of parameters in known.
You can do extra processing by first trimming leading and trailing spaces, then split along /\s+/.
I'm not sure of your character-set that your PluginName can contain, or the parameters/values, but in case they are limited you can use the following regex:
/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/
This will capture the plugin name followed by any list of alpha-numeric parameters with their values. The output can be seen with:
<?
$str = '#include_plugin:PluginName param1=value1 param2=value2#
#include_plugin:BestSellers limit=5 fromCategory=123#';
$regex = '/#include_plugin:((?:\w+)(?:\s+[a-zA-Z0-9]+=[a-zA-Z0-9]+)*)#/';
$matches = array();
preg_match_all($regex, $str, $matches);
print_r($matches);
?>
This will output:
Array
(
[0] => Array
(
[0] => #include_plugin:PluginName param1=value1 param2=value2#
[1] => #include_plugin:BestSellers limit=5 fromCategory=123#
)
[1] => Array
(
[0] => PluginName param1=value1 param2=value2
[1] => BestSellers limit=5 fromCategory=123
)
)
To get the array in the format you need, you can iterate through the results with:
$plugins = array();
foreach ($matches[1] as $match) {
$plugins[] = explode(' ', $match);
}
And now you'll have the following in $plugins:
Array
(
[0] => Array
(
[0] => PluginName
[1] => param1=value1
[2] => param2=value2
)
[1] => Array
(
[0] => BestSellers
[1] => limit=5
[2] => fromCategory=123
)
)
$string = "#include_plugin:PluginName1 param1=value1 param2=value2# #include_plugin:PluginName2#";
preg_match_all('/#include_plugin:([a-zA-Z0-9]+)\s?([^#]+)?/', $string, $matches);
var_dump($matches);
is this what you are looking for?
array(3) {
[0]=>
array(2) {
[0]=>
string(55) "#include_plugin:PluginName1 param1=value1 param2=value2"
[1]=>
string(27) "#include_plugin:PluginName2"
}
[1]=>
array(2) {
[0]=>
string(11) "PluginName1"
[1]=>
string(11) "PluginName2"
}
[2]=>
array(2) {
[0]=>
string(27) "param1=value1 param2=value2"
[1]=>
string(0) ""
}
}
This Regex will give you multiple groups, one for each plugin.
((?<=#include_plugin:)(.+))
I have an sorted array which contains first names of people.
This array has lots of names which are same.
I want to output only duplicate names.
Example,
input array:
Array
(
[0] => Abbas
[1] => Abhay
[2] => Abhinav
[3] => Abhishek
[4] => Aditya
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
It should return
Array
(
[5] => Ahmed
[6] => Ahmed
[7] => Ajay
[8] => Ajay
}
Use this code:
# assuming your original array is $arr
array_unique(array_diff_assoc($arr, array_unique($arr)));
It will return unique duplicates but if you want non-unique duplicates then use:
array_diff_assoc($arr, array_unique($arr));
EDIT: Based on your comments, try this code:
$uarr = array_unique($arr);
var_dump(array_diff($arr, array_diff($uarr, array_diff_assoc($arr, $uarr))));
OUTPUT
array(4) {
[5]=>
string(5) "Ahmed"
[6]=>
string(5) "Ahmed"
[7]=>
string(4) "Ajay"
[8]=>
string(4) "Ajay"
}
You could use this function http://php.net/manual/en/function.array-unique.php to get an array withoutt he duplicate values, then you can use this function http://www.php.net/manual/en/function.array-intersect.php to find the differences, maintaining key association.
Try array_reduce:
http://php.net/manual/en/function.array-reduce.php
Create a callback that populates an array using the values from $input as keys, and increments them accordingly. And then filter those that appear more than once.
Using array_count_values() to count up everything in the array, then filter the resulting array to show only the ones where there's more than 1:
$input = array(.... your names here ....);
$counts = array_count_values($input);
$duplicates = array_filter($counts, function element { return ($element > 1) });
Doing that off the top of my head, but should be enough to get you started.