preg_replace php to replace repeated characters - php

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

Related

PhP regex for a string, what would be the best way to do it?

I have an array with rule field that has a string like this:
FREQ=MONTHLY;BYDAY=3FR
FREQ=MONTHLY;BYDAY=3SA
FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR
FREQ=MONTHLY;UNTIL=20170527T100000Z;BYDAY=4SA
FREQ=WEEKLY;BYDAY=SA
FREQ=WEEKLY;INTERVAL=2;BYDAY=TH
FREQ=WEEKLY;BYDAY=TH
FREQ=WEEKLY;UNTIL=20170610T085959Z;BYDAY=SA
FREQ=MONTHLY;BYDAY=2TH
Each line is a different array, I am giving a few clues to get an idea of what I need.
What I need is to write a regex that would take off all unnecessary values.
So, I don't need FREQ= ; BYDAY= etc. I basically need the values after = but each one I want to store in a different variable.
Taking third one as an example it would be:
$frequency = WEEKLY
$until = 20170728T080000Z
$day = MO, TU, WE, TH, FR
It doesn't have to be necessarily one regex, there can be one regex for each value. So I have one for FREQ:
preg_match("/[^FREQ=][A-Z]+/", $input_line, $output_array);
But I can't do it for the rest unfortunately, how can I solve this?
The only way to go would be PHP array destructuring:
$str = "FREQ=WEEKLY;UNTIL=20170728T080000Z;BYDAY=MO,TU,WE,TH,FR";
preg_match_all('~(\w+)=([^;]+)~', $str, $matches);
[$freq, $until, $byday] = $matches[2]; // As of PHP 7.1 (otherwise use list() function)
echo $freq, " ", $until, " ", $byday;
// WEEKLY 20170728T080000Z MO,TU,WE,TH,FR
Live demo
Be more general
Using extract function:
preg_match_all('~(\w+)=([^;]+)~', $str, $m);
$m[1] = array_map('strtolower', $m[1]);
$vars = array_combine($m[1], $m[2]);
extract($vars);
echo $freq, " ", $until, " ", $byday;
Live demo
Notice: For this problem, I recommend the generell approach #revo posted, it's concise and safe and easy on the eyes -- but keep in mind, that regular expressions come with a performance penalty compared to fixed string functions, so if you can use strpos/substr/explode/..., try to use them, don't 'knee-jerk' to a preg_-based solution.
Since the seperators are fixed and don't seem to occur in the values your are interested in, and you furthermore rely on knowledge of the keys (FREQ:, etc) you don't need regular-expressions (as much as I like to use them anywhere I can, and you can use them here); why not simply explode and split in this case?
$lines = explode("\n", $text);
foreach($lines as $line) {
$parts = explode(';', $line);
$frequency = $until = $day = $interval = null;
foreach($parts as $part) {
list($key, $value) = explode('=', $part);
switch($key) {
case 'FREQ':
$frequency = $value;
break;
case 'INTERVAL':
$interval = $value;
break;
// and so on
}
}
doSomethingWithTheValues();
}
This may be more readable and efficient if your use-case is as simple as stated.
You need to use the Pattern
;?[A-Z]+=
together with preg_split();
preg_split('/;?[A-Z]+=/', $str);
Explanation
; match Semikolon
? no or one of the last Character
[A-Z]+ match one or more uppercase Letters
= match one =
If you want to have each Line into a seperate Array, you should do it this Way:
# split each Line into an Array-Element
$lines = preg_split('/[\n\r]+/', $str);
# initiate Array for Results
$results = array();
# start Looping trough Lines
foreach($lines as $line){
# split each Line by the Regex mentioned above and
# put the resulting Array into the Results-Array
$results[] = preg_split('/;?[A-Z]+=/', $line);
}

How to split and count the words with single quotes (')?

I want to split word like who's and count it into 2 words:
who = 1
s = 1
I think it will use preg_split to do this job, but I don't understand how to do it.
You may use explode() to get it.
$word= "who's'who";
$results= array();
$parts = explode ("'", $word);
foreach ($parts as $part) $results[$part]++;
You then may output like:
foreach ($results as $word => $count) echo $word . " = " . $count. "<br>";
The output should be:
who = 2
s = 1
You could use preg_split:
$str = "who's";
$words = preg_split("/\'/", $str);
But, as others have mentioned, explode is far easier, and will have better performance

How to: compare array elements with a String

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

mb_eregi_replace multiple matches get them

$string = 'test check one two test3';
$result = mb_eregi_replace ( 'test|test2|test3' , '<$1>' ,$string ,'i');
echo $result;
This should deliver: <test> check one two <test3>
Is it possible to get, that test and test3 was found, without using another match function ?
You can use preg_replace_callback instead:
$string = 'test check one two test3';
$matches = array();
$result = preg_replace_callback('/test|test2|test3/i' , function($match) use ($matches) {
$matches[] = $match;
return '<'.$match[0].'>';
}, $string);
echo $result;
Here preg_replace_callback will call the passed callback function for each match of the pattern (note that its syntax differs from POSIX). In this case the callback function is an anonymous function that adds the match to the $matches array and returns the substitution string that the matches are to be replaced by.
Another approach would be to use preg_split to split the string at the matched delimiters while also capturing the delimiters:
$parts = preg_split('/test|test2|test3/i', $string, null, PREG_SPLIT_DELIM_CAPTURE);
The result is an array of alternating non-matching and matching parts.
As far as I know, eregi is deprecated.
You could do something like this:
<?php
$str = 'test check one two test3';
$to_match = array("test", "test2", "test3");
$rep = array();
foreach($to_match as $val){
$rep[$val] = "<$val>";
}
echo strtr($str, $rep);
?>
This too allows you to easily add more strings to replace.
Hi following function used to found the any word from string
<?php
function searchword($string, $words)
{
$matchFound = count($words);// use tha no of word you want to search
$tempMatch = 0;
foreach ( $words as $word )
{
preg_match('/'.$word.'/',$string,$matches);
//print_r($matches);
if(!empty($matches))
{
$tempMatch++;
}
}
if($tempMatch==$matchFound)
{
return "found";
}
else
{
return "notFound";
}
}
$string = "test check one two test3";
/*** an array of words to highlight ***/
$words = array('test', 'test3');
$string = searchword($string, $words);
echo $string;
?>
If your string is utf-8, you could use preg_replace instead
$string = 'test check one two test3';
$result = preg_replace('/(test3)|(test2)|(test)/ui' , '<$1>' ,$string);
echo $result;
Oviously with this kind of data to match the result will be suboptimal
<test> check one two <test>3
You'll need a longer approach than a direct search and replace with regular expressions (surely if your patterns are prefixes of other patterns)
To begin with, the code you want to enhance does not seem to comply with its initial purpose (not at least in my computer). You can try something like this:
$string = 'test check one two test3';
$result = mb_eregi_replace('(test|test2|test3)', '<\1>', $string);
echo $result;
I've removed the i flag (which of course makes little sense here). Still, you'd still need to make the expression greedy.
As for the original question, here's a little proof of concept:
function replace($match){
$GLOBALS['matches'][] = $match;
return "<$match>";
}
$string = 'test check one two test3';
$matches = array();
$result = mb_eregi_replace('(test|test2|test3)', 'replace(\'\1\')', $string, 'e');
var_dump($result, $matches);
Please note this code is horrible and potentially insecure. I'd honestly go with the preg_replace_callback() solution proposed by Gumbo.

How can I use a string to get a value from a multi dimensional array?

Say this is my string
$string = 'product[0][1][0]';
How could I use that string alone to actually get the value from an array as if I had used this:
echo $array['product'][0][1][0]
I've messed around with preg_match_all with this regex (/\[([0-9]+)\]/), but I am unable to come up with something satisfactory.
Any ideas? Thanks in advance.
You could use preg_split to get the individual array indices, then a loop to apply those indices one by one. Here's an example using a crude /[][]+/ regex to split the string up wherever it finds one or more square brackets.
(Read the [][] construct as [\]\[], i.e. a character class that matches right or left square brackets. The backslashes are optional.)
function getvalue($array, $string)
{
$indices = preg_split('/[][]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($indices as $index)
$array = $array[$index];
return $array;
}
This is prettttty hacky, but this will work. Don't know how much your array structure is going to change, either, this won't work if you get too dynamic.
$array = array();
$array['product'][0][1][0] = "lol";
$string = 'product[0][1][0]';
$firstBrace = strpos( $string, "[" );
$arrayExp = substr($string, $firstBrace );
$key = substr( $string, 0, $firstBrace );
echo $arrayExp, "<br>";
echo $key, "<br>";
$exec = "\$val = \$array['".$key."']".$arrayExp.";";
eval($exec);
echo $val;
What about using eval()?
<?php
$product[0][1][0] = "test";
eval ("\$string = \$product[0][1][0];");
echo $string . "\n";
die();
?>

Categories