I have predefined an array:
$tags = array('PHP', 'Webdesign', 'Wordpress', 'Drupal', 'SQL');
Now I am inputting a value into a text area:
$text = 'Working With Wordpress Shortcodes and doing some NoSQL and SQL';
How can I compare the string value with the predefined array?
The desired result I want based on the above is 'Wordpress' and 'SQL'
Can I do it in PHP and JQuery?
Also, if it will contain a regular expression like
Working With Wordpress; Shortcodes: and doing some NoSQL and ""SQL
Then what to do?
You should split your string like so
$array = explode( ' ', $text );
Then compare like so
$result_array = array_intersect($tags, $array);
Now result_array will contain every value that is in both of the arrays :)
Using explode split the string to works, than for each word check in_array
$words = explode(' ', $text);
$result = array();
foreach ($words as $word) {
if (in_array($word, $tags)) {
$result[] = $word;
}
}
Note: the comparision will be case-sensitivive
foreach(explode(' ', $text) as $word) {
if(in_array($word, $tags)) {
// This word is in our tags array, do something.
}
}
i have found some solution and it works perfectly for me.
Firstly i am rearranged the string with a "," separated using
var valsp = $('#desc').val();
var results = valsp.split(/\W+/);
after this just using inArray() i am getting the desired result
Hope it will help to others
Related
A string look like this:
$string = 'Super this is a test this is a test';
Output should be:
Super
I am trying to remove duplicate words completly from a string. What I have found is:
echo implode(' ',array_unique(explode(' ', $string)));
but here is the output:
Super this is a test
Thank you for a easy way to do this.
That's because array_unique() reduces duplicates to one value:
Takes an input array and returns a new array without duplicate values.
src
You need to loop the array first (though can imagine a lot of creative array_filter/array_walk stuff possibly):
$string = 'Super this is a test this is a test';
# first explode it
$arr = explode(' ', $string);
# get value count as var
$vals = array_count_values($arr);
foreach ($arr as $key => $word)
{
# if count of word > 1, remove it
if ($vals[$word] > 1) {
unset($arr[$key]);
}
}
# glue whats left together
echo implode(' ', $arr);
fiddle
And as a function for general project-use:
function rm_str_dupes(string $string, string $explodeDelimiter = '', string $implodeDelimiter = '')
{
$arr = explode($explodeDelimiter, $string);
$wordCount = array_count_values($arr);
foreach ($arr as $key => $word)
{
if ($wordCount[$word] > 1) {
unset($arr[$key]);
}
}
return implode($implodeDelimiter, $arr);
}
# example usage
echo rm_str_dupes('Super this is a test this is a test');
You can also use array functions and do this in one line without using foreach.
echo implode(' ', array_keys(array_intersect(array_count_values(explode(' ', $string)),[1])));
In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);
I've been using the recurisve SpinTax processor as seen here, and it works just fine for smaller strings. However, it begins to run out of memory when the string goes beyond 20KB, and it's becoming a problem.
If I have a string like this:
{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!
and I want to have random combinations of the words put together, and not use the technique as seen in the link above (recursing through the string until there are no more words in curly-braces), how should I do it?
I was thinking about something like this:
$array = explode(' ', $string);
foreach ($array as $k=>$v) {
if ($v[0] == '{') {
$n_array = explode('|', $v);
$array[$k] = str_replace(array('{', '}'), '', $n_array[array_rand($n_array)]);
}
}
echo implode(' ', $array);
But it falls apart when there are spaces in-between the options for the spintax. RegEx seems to be the solution here, but I have no idea how to implement it and have much more efficient performance.
Thanks!
You could create a function that uses a callback within to determine which variant of the many potentials will be created and returned:
// Pass in the string you'd for which you'd like a random output
function random ($str) {
// Returns random values found between { this | and }
return preg_replace_callback("/{(.*?)}/", function ($match) {
// Splits 'foo|bar' strings into an array
$words = explode("|", $match[1]);
// Grabs a random array entry and returns it
return $words[array_rand($words)];
// The input string, which you provide when calling this func
}, $str);
}
random("{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!");
random("{This|That} is so {awesome|crazy|stupid}!");
random("{StackOverflow|StackExchange} solves all of my {problems|issues}.");
You can use preg_replace_callback() to specify a replacement function.
$str = "{Hello|Howdy|Hola} to you, {Mr.|Mrs.|Ms.} {Smith|Williams|Austin}!";
$replacement = function ($matches) {
$array = explode("|", $matches[1]);
return $array[array_rand($array)];
};
$str = preg_replace_callback("/\{([^}]+)\}/", $replacement, $str);
var_dump($str);
So I have a list of values like that goes like this:
values: n,b,f,d,e,b,f,ff`
I want to use preg_replace() in order to remove the repeated characters from the list of values (it will be inserted to a MySQL table). b and f are repeated. ff should not count as f because it's a different value. I know that \b \b will be used for that. I am not sure on how to take out the repeated b and f values as well as the , that precedes each value.
If the list is in a string looking like the example above, a regex is overkill. This does it just as well;
$value = implode(',', array_unique(explode(',', $value)));
I agree with other commenters that preg_replace is not the way to go; but, since you ask, you can write:
$str = preg_replace('/\b(\w+),(?=.*\b\1\b)/', '', $str);
That will remove all but the last instance of a given list-element.
No need for regex for this:
join(",", array_unique(split(",", $values)))
If this list you're dealing with is a simple string, a possible solution would be like this:
function removeDuplicates($str) {
$arr = explode(',', $str);
$arr = array_unique($arr);
return implode(',', $arr);
}
$values = removeDuplicates('n,b,f,d,e,b,f,ff'); // n,b,f,d,e,ff
$str = "values: n,b,f,d,e,b,f,ff";
$arr = array();
preg_match("/(values: )([a-z,]+)/i", $str, $match);
$values = explode(",", $match[2]);
foreach($values AS $value){
if(!$arr[$value]) $arr[$value] = true;
}
$return = $match[1];
foreach($arr AS $a){
$return .= ($i++ >= 1 ? "," : "").$a;
}
I have a string which contains quite a bit of data. I want to split the data into a 2D array. The data in the string is split by a ~ (tilde) for the columns and a : (colon) for the different rows.
An example string could be: "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry".
Thanks.
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$array = explode(':', $string);
foreach($array as &$value) $value = explode('~', $value);
Functional way (PHP 5.3.x needed):
$string = "London~10~20~cold:New York~23~53~hot:Madrid~43~12~dry";
$map = array_map(function($el) {
return explode('~', $el);
}, explode(':', $string));
Another alternative would be:
preg_match_all('/(.*?)~(.*?)~(.*?)~(.*?)(?:$|:)/', $string, $array,
PREG_SET_ORDER);
It's more cumbersome in that you have to predefine the column format. It also returns the complete match in each rows [0]. Otherwise (due to PREG_SET_ORDER) it's in your desired 2d format.
Just posting it here to please and annoy the microoptimizers at the same time. Despite the common Stackoverflow meme, the regex is three times faster than the explode loop.
You can split data in php with explode().
So first you have to split the string, than you have to split your entries again with explode().
$data = explode(':', $string);
$array = array();
foreach($data as $d) {
$d = explode('~', $d);
$array[] = $d; //e.g. $array[0][0] --> London
//$array[$d[0]] = array('temperature' => $d[1], 'dont-know' => $d[2], 'climate' => $d[3]); //e.g. $arra['London'] => array(...)
}
A "functional" style
$array = array_map(function($value) {
return explode('~', $value);
}, explode(':',$string););