PHP regex preg_grep change string path - php

I have array:
$array = array(
"C:/path/something1/something2/dir",
"C:/path1/something/something2/dir2\nextdir",
"C:/path2/something/dir2\nextdir\next",
"C:/path/something3/something6/something7/dir5\nextdir2\next"
);
All that is before the last sign "/" with him to disappear.
I want something like that:
$array = array(
"dir",
"dir2\nextdir",
"dir2\nextdir\next",
"dir5\nextdir2\next"
);
I need regex
$new_array = preg_grep("/regex/", $array);
I have no idea how to write a regex.
I dont want like that:
foreach($array as $key => $val) {
$e = explode("/", $val);
$new_array[] = end($e);
}

preg_grep() does not change/replace the values, it returns the items that match the given regular expression. If you must use regex and replace the values, take a look at preg_replace() instead:
$array = preg_replace('~.*/~', '', $array);
var_dump($array);
Output
array(4) {
[0]=> string(3) "dir"
[1]=> string(12) "dir2\nextdir"
[2]=> string(17) "dir2\nextdir\next"
[3]=> string(18) "dir5\nextdir2\next"
}

Related

Converting numeric array to associative array using implode or explode?

So lets say I have an array and when I var_dump(); it, it has the following output:
[1]=>
string(20) "Name: Kevin"
[2]=>
string(20) "Age: 20"
Can I manipulate it using implode or explode so that the output would look like this:
[Name]=>
string(5) "Kevin"
[Age]=>
string(2) "20"
Any help would be appreciated.
You can use explode() with trim()
$array = [];
foreach($initialArray as $data){
$exploded = explode(':',$data);
$array[trim($exploded[0])] = trim($exploded[1]);
}
Output:-https://3v4l.org/3q0i5

remove part of string after 4th slash in php

I have an array which is contains links and trying to edit those links. Trying to cut links after 4th slash.
[0]=>
string(97) "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline"
[1]=>
string(105) "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline"
[2]=>
string(91) "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline"
expected output is like this:
[0]=>
string(97) "https://www.nowhere.com./downtoalley/"
[1]=>
string(105) "https://www.example.com./wowar-waseda/"
[2]=>
string(91) "https://www.hey.com./gotoashbourn/"
Lengths are different, so I can't use strtok any other options for this?
Try following code:
<?php
$arr = array(
0 => "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
1 => "https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
2 => "https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");
$resultArray = array();
foreach($arr as $str) {
array_push($resultArray, current(explode("?",$str)));
}
print_r($resultArray);
?>
You can test this code here
You can use preg_replace to replace everything in each string after the fourth / with nothing using this regex
^(([^/]*/){4}).*$
which looks for 4 sets of non-/ characters followed by a /, collecting that text in capture group 1; and then replacing with $1 which gives only the text up to the 4th /:
$strings = array("https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline",
"https://www.example.com./wowar-waseda/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shinjuku-w25861/outline",
"https://www.hey.com./gotoashbourn/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=kinuta7429/outline");
print_r(array_map(function ($v) { return preg_replace('#^(([^/]*/){4}).*$#', '$1', $v); }, $strings));
Output:
Array (
[0] => https://www.nowhere.com./downtoalley/
[1] => https://www.example.com./wowar-waseda/
[2] => https://www.hey.com./gotoashbourn/
)
Demo on 3v4l.org
There is no direct function to achieve this. You can follow PHP code as below:
$explodingLimit = 4;
$string = "https://www.nowhere.com./downtoalley/?iad2=sumai-pickup&argument=CH4fRVnN&dmai=shimokita4040/outline";
$stringArray = explode ("/", $string);
$neededElements = array_slice($stringArray, 0, $explodingLimit);
echo implode("/", $neededElements);
I have made this for one element which you can use for you array. Also you can add last '/' if you need that. Hope it helps you.

PHP convert string to array with variable element length

I have a string AB0512CD123456 and using preg match how can I convert it to
Array[0]='AB';
Array[1]='05';
Array[2]='12CD12';
Array[3]='3456';
That is first element with size-2,then 2,6,4 etc.The input string may be dynamic.
If the input string length is fixed, all you need is sscanf():
var_dump(sscanf('AB0512CD123456', '%2s%2s%6s%4s'));
Output:
array(4) {
[0]=>
string(2) "AB"
[1]=>
string(2) "05"
[2]=>
string(6) "12CD12"
[3]=>
string(4) "3456"
}
Better use this:
$str="AB0512CD123456";
$Array[0] = substr($str, 0,2);
$Array[1] = substr($str, 2,2);
$Array[2] = substr($str, 4,6);
$Array[3] = substr($str, 10,4);
Works on any generalized pattern
This example makes use of sscanf as proposed by Paulo Freitas
<?php
$str="AB0512CD123456";
$pattern="2,3,4,5"; // Your pattern
$pattern=explode(",",$pattern);
foreach($pattern as $k=>$v)
{
$newpattern.="%".$v."s";
}
var_dump(sscanf($str,$newpattern));

Get particluar values from a string in PHP

My string is :
$mystring = "https://maps.google.com/?ll=37.0625,-95.677068&spn=37.188995,86.572266&t=m&z=4";
Now I want those values which I have marked as bold from the string. How can I achieve this with PHP?
Use the following functions parse_url and parse_str. You could do something like this the following
$url = "https://maps.google.com/?ll=**37.0625,-95.677068**&spn=**37.188995,86.572266**&t=m&z=4";
$parts = parse_url($url);
if(isset($parts['query'])) {
parse_str(urldecode($parts['query']), $result);
print_r($result)
}
use explode or parse_url or parse_str
you'll have to use $_GET['ll'] and $_GET['spn'] to repectively obtain 37.0625,-95.677068 and 37.188995,86.572266
Here regular expression will be most efficient to parse your required values.
$url = "https://maps.google.com/?ll=37.0625,-95.677068&spn=37.188995,86.572266&t=m&z=4";
$regex = "/[-]*\d+.\d*/";
preg_match_all($regex,$url,$out, PREG_PATTERN_ORDER);
// $out = array(1) { [0]=> array(4) { [0]=> string(7) "37.0625" [1]=> string(10) "-95.677068" [2]=> string(9) "37.188995" [3]=> string(9) "86.572266" } }

how can split the result set array to string in php

i need help. i was developed a page in smarty , i got a result set from a query and i need to change the result set to string and stored in text area
my query is given below
select val from test
my result set is print in var_dump in controller
{ [0]=> array(1) { ["val"]=> string(1) "c" } [1]=> array(1) { ["val"]=> string(3) "c++" } [2]=> array(1) { ["val"]=> string(4) "java" } [3]=> array(1) { ["val"]=> string(3) "PHP" } }
i need to change in to sting like c,c++,java,PHP
the changing function is preformed only controller
ple help me.. and thk adv
Use foreach for that. See more information here - http://php.net/manual/en/control-structures.foreach.php .
Example -
$array = Array("333", "222", "111");
foreach($array as $string) {
echo $string.'<br />';
}
Another solution would be to use implode.
See more information here - http://php.net/manual/en/function.implode.php and again a small example -
$array = Array("333", "222", "111");
$strings = implode(",", $array); // comma in first quotes are seperator, you can set it also to " " for a single space.
echo $strings; // In this case it will output 333,222,111 if you would set it to empty space then it would output 333 222 11
EDIT:
For writing in file you must use file functions.
Check this link - http://php.net/manual/en/function.file-put-contents.php
example -
// your file
$file = 'sample.txt';
$array = Array("333", "222", "111");
// Add all strings to $content.
foreach($array as $string) {
$content .= $string.'<br />';
}
// write everything in file
file_put_contents($file, $content);
Suggestion:
When you are writing SQL queries, I would suggest that you already now start learning to write them correctly, so they are easier to read.
For example, your query -
select val from test
Could be changed to -
SELECT `val` FROM `test`
which is alot easier to read and understand.
If You need to join all array with some delimeters, then use implode.
Example:
$arr = array("hi", "peter!", "how", "are", "you");
echo implode(" ", $arr) . "?";
//output
// hi peter! how are you?
If you want a string separated by commas, you must use the implode function
string implode ( string $glue , array $pieces )
glue: Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.
pieces:The array of strings to implode.
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
http://www.php.net/manual/en/function.implode.php
Example
$array = Array("333", "222", "111");
$string = explode(',', $array);
returns
"333,222,111"
if you want spaces:
$string = explode(' ', $array);
returns
"333 222 111"

Categories