Remove characters from string based on user input - php

Suppose I have a string:
$str="1,3,6,4,0,5";
Now user inputs 3.
I want that to remove 3 from the above string such that above string should become:
$str_mod="1,6,4,0,5";
Is there any function to do the above?

You can split it up, remove the one you want then whack it back together:
$str = "1,3,6,4,0,5";
$userInput = 3;
$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));
echo implode(',', $result); // 1,6,4,0,5
Bonus: Make $userInput an array at the definition to take multiple values out.

preg_replace('/\d[\D*]/','','1,2,3,4,5,6');
in place of \d just place your digit php

If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:
$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
unset($components[$idx]);
}
$string = implode(',', $components);
The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.

Related

I want to add only integer values in a given string

<?php
$str = "1,2,3,4,b,6,c,7,8,f,9";
?>
I want to add only integer values in the above string... Can anyone suggest me an answer ? I tried explode function which will explode the character and return the integer values... But I failed to do so...
You need to split them up, filter anything that's not numeric out, then add them:
$chars = explode(',', $str);
$chars = array_filter($chars, 'is_numeric');
echo array_sum($chars); // 40

Search and replace all lines in a multiline string

I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs

In comma delimited string is it possible to say "exists" in php

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

php array count includes trailing comma

I have an array which I get from an exploded url (using $_GET).
The elements in the url are separated by commas but when I COUNT the elements the result includes the final comma. Eg: '?list=jonny,sally,bob,' returns '4' when '?list=jonny,sally,bob' returns '3'. I can't avoid the final comma as they are genrated with them automatically but I need to return 3 on both examples. Any ideas please?? Thanks
$list = explode(",", $_GET['list']);
$listCount = count($list);
//$listCount =(int)$listCount -1;
//$list[$listCount]=str_replace($list[$listCount],',','');
echo $listCount;
NB: the commented out lines are a failed attempt to remove the comma. But $list[$listCount] ,ie the final array element doesn't seem to exist even though it is counted
If you want to trim any extra commas at the start or end of the string, use trim(). If you want it at the end of the string, you can use rtrim().
$list = explode(",", $_GET['list']);
to
$list = explode(",", trim($_GET['list'], ','));
Trim any commas first:
$strList = rtrim($_GET['list'], ",")
$arrList = explode(",", $strList);
Array_filter will remove any empty values from your array, so in case you have two commas in a row, it will remove empty values caused by that also.
$list = array_filter(explode(",", $_GET['lists']));

PHP RegEx/Substring to get ID from a string

Here is my string:
**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**
I want to take the last section /NHg5XdqFb5b/ and remove the slashes.
Also are there any tools available to attemtp to work this out?
You can do this by:
<?php
$id = explode("/", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**");
$myID = $id[count($id)-2];
?>
Or if you want to use regex: (make sure all ids are 11 in length)
preg_match("/[a-zA-Z0-9]{11}/i", "**tag:my.domain.com,2011-07-13:/895645783/posts/NHg5XdqFb5b/**", $matches);
echo($matches[0]);
You could do a preg_replace http://ch.php.net/preg_replace
$var = preg_replace('~.*/([^/]+)/\*\*~','$1',$var);
You can use explode, which will split the string and return an array
$arr = explode("/", your_string_here); //split string by "/"
$id = $arr[count($arr) - 2]; //in your case, get the second-last part
Alternatively,
$arr = preg_match("\/posts\/(.*?)\/", your_string_here); //matches /posts/NHg5XdqFb5b/
//$arr[0] = whole match
//$arr[1] = 1st capture group (part between brackets) in your regex, i.e. required id
$id = $arr[1];
Cheers,

Categories