How to remove any special character from php array? - php

How to remove any special character from php array?
I have array like:
$temp = array (".com",".in",".au",".cz");
I want result as:
$temp = array ("com","in","au","cz");
I got result by this way:
$temp = explode(",",str_replace(".","",implode(",",$temp)));
But is there any php array function with we can directly remove any character from all values of array? I tried and found only spaces can be removed with trim() but not for any character.

Use preg_replace function. This will replace anything that isn't a letter, number or space.
SEE DEMO
<?php
$temp = array (".com",".in",".aus",".cz");
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $temp );
print_r($temp);
//outputs
Array
(
[0] => com
[1] => in
[2] => aus
[3] => cz
)
?>

I generaly make a function
function make_slug($data)
{
$data_slug = trim($data," ");
$search = array('/','\\',':',';','!','#','#','$','%','^','*','(',')','_','+','=','|','{','}','[',']','"',"'",'<','>',',','?','~','`','&',' ','.');
$data_slug = str_replace($search, "", $data_slug);
return $data_slug;
}
And then call it in this way
$temp = array (".com",".in",".au",".cz");
for($i = 0; $i<count($temp); $i++)
{
$temp[$i] = make_slug($temp[$i]);
}
print_r($temp);
Each value of $temp will then become free of special characters
See the Demo

As a solution to your problem please execute the following code snippet
$temp = array (".com",".in",".au",".cz");
function strip_special_chars($v)
{
return str_replace('.','',$v);
}
$result[]=array_map('strip_special_chars',$temp);

Actually trim() can trim any character(s) you wish if you provide the 2nd argument (character mask). As it's name implies, this will only remove characters from the beginning and end of the string. In your case ltrim() may be more appropriate.
You can use array_map() and ltrim() together with a third parameter for the character mask like this:
$temp = array_map('ltrim', $temp, array_fill(0, count($temp), '.'));
The third parameter should be an array of arguments matching the length of the array you're processing, which is why I used array_fill() to create it.

Related

How to convert a certain type of string into an array with keys in php?

I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO

How can I get the end of a string in PHP?

Substr PHP
I have a string like http://domain.sf/app_local.php/foo/bar/33.
The last characters are the id of an element. Its length could be more than one, so I can not use:
substr($dynamicstring, -1);
In this case, it must be:
substr($dynamicstring, -2);
How can I get the characters after "/bar/" on the string without depending on the length?
To ensure you are getting an immediate section after the bar, use regular expressions:
preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33
You can use explode(), like this:
$id = explode('/',$var);
And take the element where you had the id.
You could use explode('/', $dynamicstring) to split the string into an array of the strings inbetween each /. Then you could use end() on the result of this to get the last part.
$id = end(explode('/', $dynamicstring));
Try this:
$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';
// split your string into an array with /
$parts = explode('/', $dynamicstring);
// move the array pointer to the end
end($parts);
// return the current position/value of the $parts array
$id = current($parts);
// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);
echo $id;
// $id => 33
Test it yourself here.
You can use a regular expression to do it:
$dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
echo $m[1];
}
I tested it out myself before answering. Other answers are reasonable too, but this will work according to your need...
<?php
$url = "http://domain.sf/app_local.php/foo/bar/33";
$id = substr($url, strpos($url, "/bar/") + 5);
echo $id;
Please find the below answer.
$str = "http://domain.sf/app_local.php/foo/bar/33";
$splitArr = explode('/', explode('//', $str)[1]);
var_dump($splitArr[count($splitArr)-1]);

How to get a range of arrays

I have a code which I have to explode my text using "*" as a delimiter.
I have a pattern that always the array [0] and [1] will be excluded and the rest of them need to be included inside a variable, but my problem is that I don't know how to catch dynamically the rest of the arrays that I have to put them all together inside of it.
Specially because my text may have more "*" and explode into more parts, but I have to get them all together. Excluding the [0] and [1]
$item= explode("*",$c7);
print_r($item);
//so now that I know which are my [0] and [1] arrays I need to get the rest of them inside of another variable
$variable = ?? //the rest of the $item arrays
$str = 'a*b*c*d*e';
$newStr = implode('*', array_slice(explode('*', $str), 2)); // OUTPUT: c*d*e
explode() is used to chunk the string by a delimiter
implode() is used to build a string again from chunks
array_slice() is used to select a range of the elements
I realise an answer was already accepted, but explode has a third argument for this, and with end you can grab that last, non-split part:
$str = 'a*b*c*d*e';
$res = end(explode("*", $str, 3));
$res gets this value as a result:
c*d*e
I think based off of your question, if I interpreted it correctly something like below will be useful.
USING A LOOP
$str = "adssa*asdASD*AS*DA*SD*ASD*AS*DAS*D";
$parts = explode("*", $str);
$newStr = "";
for ($i = 2; $i < count($parts); ++$i) {
$newStr .= $parts[$i];
}

PHP Regex for a specific numeric value inside a comma-delimited integer number string

I am trying to get the integer on the left and right for an input from the $str variable using REGEX. But I keep getting the commas back along with the integer. I only want integers not the commas. I have also tried replacing the wildcard . with \d but still no resolution.
$str = "1,2,3,4,5,6";
function pagination()
{
global $str;
// Using number 4 as an input from the string
preg_match('/(.{2})(4)(.{2})/', $str, $matches);
echo $matches[0]."\n".$matches[1]."\n".$matches[1]."\n".$matches[1]."\n";
}
pagination();
How about using a CSV parser?
$str = "1,2,3,4,5,6";
$line = str_getcsv($str);
$target = 4;
foreach($line as $key => $value) {
if($value == $target) {
echo $line[($key-1)] . '<--low high-->' . $line[($key+1)];
}
}
Output:
3<--low high-->5
or a regex could be
$str = "1,2,3,4,5,6";
preg_match('/(\d+),4,(\d+)/', $str, $matches);
echo $matches[1]."<--low high->".$matches[2];
Output:
3<--low high->5
The only flaw with these approaches is if the number is the start or end of range. Would that ever be the case?
I believe you're looking for Regex Non Capture Group
Here's what I did:
$regStr = "1,2,3,4,5,6";
$regex = "/(\d)(?:,)(4)(?:,)(\d)/";
preg_match($regex, $regStr, $results);
print_r($results);
Gives me the results:
Array ( [0] => 3,4,5 [1] => 3 [2] => 4 [3] => 5 )
Hope this helps!
Given your function name I am going to assume you need this for pagination.
The following solution might be easier:
$str = "1,2,3,4,5,6,7,8,9,10";
$str_parts = explode(',', $str);
// reset and end return the first and last element of an array respectively
$start = reset($str_parts);
$end = end($str_parts);
This prevents your regex from having to deal with your numbers getting into the double digits.

Querystring parameter explode str_replace array works for only 1 of the delimiters

I am using a explode and str_replace on the get parameter of the query string URL. My goal is to split the strings by certain characters to get to the value in the string that I want. I am having issues. It should work but doesn't.
Here are two samples of links with the query strings and delimiters I'm using to str_replace.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst
as you can see the URL above parameter is position and the value is data-analyst. The delimiter is the dash -.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst
and this URL above uses same parameter position and value is business+systems+analyst. The delimiter is the + sign.
The value I am trying to get from the query string is the word analyst. It is the last word after the delimiters.
Here is my code which should do the trick, but doesn't for some reason.
$last_wordPosition = str_replace(array('-', '+')," ", end(explode(" ",$position)));
It works if the delimiter is a + sign, but fails if the delimiter is a - sign.
Anyone know why?
You have things in the wrong order:
$last_wordPosition = end(explode(" ", str_replace(array('-', '+'), " ", $position)));
You probably want to split it up so as to not get the E_STRICT error when not passing an variable to end:
$words = explode(" ", str_replace(array('-', '+'), " ", $position));
echo end($words);
Or something like:
echo preg_replace('/[^+-]+(\+|-)/', '', $position);
As #MarkB suggested you should use parse_url and parse_str since it is more appropriate in your case.
From the documentation of parse_url:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
From the documentation of parse_str:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
So here is what you want to do:
$url1 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst';
$url2 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst';
function mySplit($str)
{
if (preg_match('/\-/', $str))
$strSplited = split('-', $str);
else
$strSplited = split(' ', $str);
return $strSplited;
}
parse_str(parse_url($url1)['query'], $output);
print_r($values = mySplit($output['position']));
parse_str(parse_url($url2)['query'], $output);
print_r($values = mySplit($output['position']));
OUTPUT
Array
(
[0] => data
[1] => analyst
)
Array
(
[0] => business
[1] => systems
[2] => analyst
)
You said that you needed the last element of those values. Therefore you could find end and reset useful:
echo end($values);
reset($values);
Answering my own question to show how I ended up doing this. Seems like way more code than what the accepted answer is, but since I was suggested to use parse_url and parse_str but couldn't get it working right, I did it a different way.
function convertUrlQuery($query) {
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arrayQuery = convertUrlQuery($_SERVER['QUERY_STRING']); // Returns - Array ( [occupation] => designer [position] => webmaster+or+website-designer )
$array_valueOccupation = $arrayQuery['occupation']; // Value of occupation parameter
$array_valuePosition = $arrayQuery['position']; // Value of position parameter
$split_valuePosition = explode(" ", str_replace(array('-', '+', ' or '), " ", $array_valuePosition)); // Splits the value of the position parameter into separate words using delimeters (- + or)
then to access different parts of the array
print_r($arrayQuery); // prints the array
echo $array_valueOccupation; // echos the occupation parameters value
echo $array_valuePosition; // echos the position parameters value
print_r($split_valuePosition); // prints the array of the spitted position parameter
foreach ($split_valuePosition as $value) { // foreach outputs all the values in the split_valuePosition array
echo $value.' ';
}
end($split_valuePosition); // gets the last value in the split_valuePosition array
implode(' ',$split_valuePosition); // puts the split_valuePosition back into a string with only spaces between each word
which outputs the following
arrayQuery = Array
(
[occupation] => analyst
[position] => data-analyst
)
array_valueOccupation = analyst
array_valuePosition = data-analyst
split_valuePosition = Array
(
[0] => data
[1] => analyst
)
foreach split_valuePosition =
- data
- analyst
end split_valuePosition = analyst
implode split_valuePosition = data analyst

Categories