php regex how to remove duplicate strings - php

here is a long string like"abc,adbc,abcf,abc,adbc,abcf"
I want to use regex to remove the duplicate strings which are seperated by comma
the following is my codes, but the result is not what I expect.
$a='abc,adbc,abcf,abc,adbc,abcf';
$b=preg_replace('/(,[^,]+,)(?=.*?\1)/',',',','.$a.',');
echo $b;
output:,adbc,abc,adbc,abcf,
It should be : ,abc,adbc,abcf,
please point my problem. thanks.

Here I am sharing simple php logic instead regex
$a='abc,adbc,abcf,abc,adbc,abcf';
$pieces = explode(",", $a);
$unique_values = array_unique($pieces);
$string = implode(",", $unique_values);

Here is positive lookahead base attempt on regex based solution to OP's problem.
$arr = array('ball ball code', 'abcabc bde bde', 'awycodeawy');
foreach($arr as $str)
echo "'$str' => '" . preg_replace('/(\w{2,})(?=.*?\\1)\W*/', '', $str) ."'\n";
OUTPUT
'ball ball code' => 'ball code'
'abcabc bde bde' => 'abc bde'
'awycodeawy' => 'codeawy'
As you can for the input 'awycodeawy' it makes it to 'codeawy' instead of 'awycode'. The reason is that it is possible to find a variable length lookahead something which is not possible for lookbehind.

You can also try
echo implode(",", array_unique(preg_split(",", $yourLongString)));

Try this....
$string='abc,adbc,abcf,abc,adbc,abcf';
$exp = explode(",", $string);
$arr = array_unique($exp);
$output=implode(',', $arr);

Related

replacing letters with numbers

So i've been trying to get this bit of code to work all day and haven't been able to do it... I wnat to be able to replace letters with a number (or just a value) from an array. this is the code i've got:
$l2n =
array(
'a'=>'1',
'b'=>'2',
'c'=>'3',
'd'=>'4',
'e'=>'5',
'f'=>6,
'g'=>7,
'h'=>8,
'i'=>9,
'j'=>10,
'k'=>11,
'l'=>12,
'm'=>13,
'n'=>14,
'o'=>15,
'p'=>16,
'q'=>17,
'r'=>18,
's'=>19,
't'=>20,
'u'=>21,
'v'=>22,
'w'=>23,
'x'=>24,
'y'=>25,
'z'=>16
);
$string = str_split($string);
$explode = array_shift($string);
if($l2n[$explode] == $explode)
{
echo $l2n[$explode];
}
else
{
echo $l2n['a'];
}
I tried to use Preg_replace but i've never had a good expereince with that function. so If anybody could help me out, hint me in the correct direction, that'd be great.
You can just use str_replace once you've used array_keys and array_values to get each side of the array:
$keys = array_keys($l2n);
$values = array_values($l2n);
$yourstring = 'Hello world!';
echo str_replace($keys, $values, $yourstring);
// H5121215 231518124!
Demo: https://eval.in/77453
Docs:
http://php.net/str_replace
http://php.net/array_keys
http://php.net/array_values
You can simply do:
$string = preg_replace(array_keys($l2n), array_values($l2n), $string);
From the documentation:
If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart.
Why in the world would you use an array for this? Isn't ord() what you are looking for here?
$string = "ABCDE";
foreach ( str_split($string) as $chr ) {
echo ord($chr) - 64; // or 97 if they all are lowercase
echo PHP_EOL;
}

How to split a string after every ]

I have a string in an array like format.
["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]
I am trying to split the code after every ] - The data inside the [] could vary everytime so i cant use str_split();
I want to keep all the brackets in tack so they dont cut off so i cant use explode
Thank You
Easy regex:
$s = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
preg_match_all('/\[[^\]]+\]/', $s, $m);
print_r($m[0]);
But actually it's almost json, so:
$s = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
$s = '[' . str_replace('] [', '],[', $s) . ']';
print_r(json_decode($s));
Maybe you have a fragment or modified json, so it may be easier if you have actual json.
$str = '["1","Data","time"] ["2","Data","time"] ["3","Data","time"] ["4","Data","time"]';
$newStr = trim($str,'[');
$newStr1 = trim($newStr,']');
$arr = explode('] [',$newStr1);
print_r($arr);
Easiest solution (if you don't want regular expression) would be using trim 1 char from both sides and then explode by ']['.
Example:
$string = "[123][456][789]";
$string = substr($string,1,strlen($string)-1);
$array = explode('][',$string);

preg_replace php to replace repeated characters

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

How to convert a string with numbers and spaces into an int

I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);

PHP replace string

$string = 'http://site.com/category/1/news/2134/'; // '1' is dynamic
How can I change 1 to any number I want?
Can't call parts of the string, its just a text-like variable.
It can be done with some true regex.
$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);
This replaces the number by 56.
This approach uses a regex with assertions.
$array = explode('/',$string);
$array[4] = '666';
$string = implode('/',$array);
[edit]
#People downvoting, what seems to be the problem with this approach?
Without more information, my best guess at your problem is :
<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>

Categories