$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$fdat = str_replace($filtr,"",$data);
$clean = implode(",",$fdat);
echo $clean;
this gives out put ,,searchengine,seo,search
How can I get rid of first two blank commas?
Better get the difference of your splitted arrays $exp minus $filtr:
$clean = implode(',', array_diff($exp, $filtr));
This will also avoid the chance that you will only remove a substring of another word like when removing car from bike,car,carpet should result in bike,carpet and not in bike,pet.
And if you want to allow whitespace before and after each word, consider using trim and preg_split:
$exp = preg_split('/\s*,\s*/', trim($data));
trim will remove any preceding and trailing whitespace and the pattern for preg_split allows whitespace surrounding the comma too.
I'm getting an error when trying this code you did. You can use the following to remove google & bing (that are in an array) from a comma separated string:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$diff = array_diff($exp, $filtr);
$clean = implode(",",$diff);
echo $clean;
Your piece of code could also look like this:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach ($exp as $key => $item) {
if (in_array($key, $filtr)) unset($exp[$key]);
}
$clean = implode(",",$exp);
echo $clean;
Its useful when there is few items in $data. For big arrays it would need optimizing.
You would be better if checking the value within a loop like so:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach($exp as $k => $v)
{
if(in_array($v,$filtr))
{
unset($ext[$k]);
}
}
$clean = implode(",",$ext);
echo $clean;
Related
Where can find a list of all characters that must be escaped when using preg_replace. I listed what I think are three of them in the array $ESCAPE_CHARS. What other ones am I missing.
I need this because I am going to be doing a preg replace on a form submission.
So ie.
$ESCAPE_CHARS = array("#", "^", "[");
foreach ($ESCAPE_CHARS as $char) {
$_POST{"string"} = str_replace("$char", "\\$char", $_POST{"string"});
}
$string = $_POST{"string"};
$test = "string of text";
$test = preg_replace("$string", "<b>$string</b>", $test);
Thanks!
You can use preg_quote():
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
print $keywords;
// \$40 for a g3\/400
I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!
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;
}
*strong text*i have a string like that "x", "x,y" , "x,y,h"
i want to user preg replace to remove the commas inside the double qutations and return the string as
"x", "xy" , "xyh"
You can just use a regular replace.
$mystring = str_replace(",", "", $mystring);
You dont need preg_replace() here and whereever possible you should trying to avoid it
$string = str_replace(',', '', $string);
This would work fine: http://codepad.org/lq7I5wkd
<?php
$myStr = '"x", "x,y" , "x,y,h"';
$chunks = preg_split("/\"[\s]*[,][\s]*\"/", $myStr);
for($i=0;$i<count($chunks);$i++)
$chunks[$i] = str_replace(",","",$chunks[$i]);
echo implode('","',$chunks);
?>
I use the following, which I've found is generally faster than regexp for this type of replacement
$string = '"x", "x,y" , "x,y,h"';
$temp = explode('"',$string);
$i = true;
foreach($temp as &$value) {
// Only replace in alternating array entries, because these are the entries inside the quotes
if ($i = !$i) {
$value = str_replace(',', '', $value);
}
}
unset($value);
// Then rebuild the original string
$string = implode('"',$temp);
I'd like to explode a multi-line-string like this
color:red
material:metal
to an array like this
$array['color']=red
$array['material']=metal
any idea?
Use explode(), you can use a regexp for it, but it's simple enough without the overhead.
$data = array();
foreach (explode("\n", $dataString) as $cLine) {
list ($cKey, $cValue) = explode(':', $cLine, 2);
$data[$cKey] = $cValue;
}
As mentioned in comments, if data is coming from a Windows/DOS environment it may well have CRLF newlines, adding the following line before the foreach() would resolve that.
$dataString = str_replace("\r", "", $dataString); // remove possible \r characters
The alternative with regexp can be quite pleasant using preg_match_all() and array_combine():
$matches = array();
preg_match_all('/^(.+?):(.+)$/m', $dataString, $matches);
$data = array_combine($matches[1], $matches[2]);
Try this
$value = '1|a,2|b,3|c,4|d';
$temp = explode (',',$value);
foreach ($temp as $pair)
{
list ($k,$v) = explode ('|',$pair);
$pairs[$k] = $v;
}
print_r($pairs);
explode first on line break. Prolly \n
Then explode each of the resulting array's items on : and set a new array to that key/value.