(PHP) Replace string of array elements using regex - php

I have an array
Array
(
[0] => "http://example1.com"
[1] => "http://example2.com"
[2] => "http://example3.com"
...
)
And I want to replace the http with https of each elements using RegEx. I tried:
$Regex = "/http/";
$str_rpl = '${1}s';
...
foreach ($url_array as $key => $value) {
$value = preg_replace($Regex, $str_rpl, $value);
}
print_r($url_array);
But the result array is still the same. Any thought?

You actually print an array without changing it. Why do you need regex for this?
Edited with Casimir et Hippolyte's hint:
This is a solution using regex:
$url_array = array
(
0 => "http://example1.com",
1 => "http://example2.com",
2 => "http://example3.com",
);
$url_array = preg_replace("/^http:/i", "https:", $url_array);
print_r($url_array);
PHP Demo
Without regex:
$url_array = array
(
0 => "http://example1.com",
1 => "http://example2.com",
2 => "http://example3.com",
);
$url_array = str_replace("http://", "https://", $url_array);
print_r($url_array);
PHP Demo

First of all, you are not modifying the array values at all. In your example, you are operating on the copies of array values. To actually modify array elements:
use reference mark
foreach($foo as $key => &$value) {
$value = 'new value';
}
or use for instead of foreach loop
for($i = 0; $i < count($foo); $i++) {
$foo[$i] = 'new value';
}
Going back to your question, you can also solve your problem without using regex (whenever you can, it is always better to not use regex [less problems, simpler debugging, testing etc.])
$tmp = array_map(static function(string $value) {
return str_replace('http://', 'https://', $value);
}, $url_array);
print_r($tmp);
EDIT:
As Casimir pointed out, since str_replace can take array as third argument, you can just do:
$tmp = str_replace('http://', 'https://', $url_array);

This expression might also work:
^http\K(?=:)
which we can add more boundaries, and for instance validate the URLs, if necessary, such as:
^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)
DEMO
Test
$re = '/^http\K(?=:\/\/[a-z0-9_-]+\.[a-z0-9_-]+)/si';
$str = ' http://example1.com ';
$subst = 's';
echo preg_replace($re, $subst, trim($str));
Output
https://example1.com
The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.
RegEx Circuit
jex.im visualizes regular expressions:

Related

How to extract string between two slashes php

i know that its easy to extract string between two slashes using explode() function in php, What if the string is like
localhost/used_cars/search/mk_honda/md_city/mk_toyota
i want to extract string after mk_ and till the slashes like:** honda,toyota **
any help would be highly appreciated.
I am doing like this
echo strpos(uri_string(),'mk') !== false ? $arr = explode("/", $string, 2);$first = $arr[0]; : '';
but not working because if user enter mk_honda in any position then explode() is failed to handle that.
Use regex:
http://ideone.com/DNHXsf
<?php
$input = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
preg_match_all('#/mk_([^/]*)#', $input, $matches);
print_r($matches[1]);
?>
Output:
Array
(
[0] => honda
[1] => toyota
)
Explode your string by /, then check every element of array with strpos:
$string = 'localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$parts = explode('/', $string);
$r = [];
foreach ($parts as $p) {
// use `===` as you need `mk_` in position 0
if (strpos($p, 'mk_') === 0) {
// 3 is a length of `mk_`
$r[] = substr($p, 3);
}
}
echo'<pre>',print_r($r),'</pre>';
Just try this
$str='localhost/used_cars/search/mk_honda/md_city/mk_toyota';
$str=explode('/',$str);
$final=[];
foreach ($str as $words){
(!empty(explode('_',$words)))?(isset(explode('_',$words)[1]))?$final[]=explode('_',$words)[1]:false:false;
}
$final=implode(',',$final);
echo $final;
It give output as
cars,honda,city,toyota

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.

php replace all occurances of key from array in string

maybe this is duplicate but i did't find good solution.
I have array
$list = Array
(
[hi] => 0
[man] => 1
);
$string="hi man, how are you? man is here. hi again."
It should produce $final_string = "0 1, how are you? 1 is here. 0 again."
How can I achieve it with smart way? Many thanks.
Off of the top of my head:
$find = array_keys($list);
$replace = array_values($list);
$new_string = str_ireplace($find, $replace, $string);
Can be done in one line using strtr().
Quoting the documentation:
If given two arguments, the second should be an array in the form array('from' => 'to', ...). The return value is a string where all the occurrences of the array keys have been replaced by the corresponding values. The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.
To get the modified string, you'd just do:
$newString = strtr($string, $list);
This would output:
0 1, how are you? 1 is here. 0 again.
Demo.
$text = strtr($text, $array_from_to)
See http://php.net/manual/en/function.strtr.php
preg_replace may be helpful.
<?php
$list = Array
(
'hi' => 0,
'man' => 1
);
$string="hi man, how are you? Man is here. Hi again.";
$patterns = array();
$replacements = array();
foreach ($list as $k => $v)
{
$patterns[] = '/' . $k . '/i'; // use i to ignore case
$replacements[] = $v;
}
echo preg_replace($patterns, $replacements, $string);

Split string using regular expression in php

I'm beginner in php and I have string like this:
$test = http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
And I want to split string to array like this:
Array(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
What should I do?
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg';
$testurls = explode('http://',$test);
foreach ($testurls as $testurl) {
if (strlen($testurl)) // because the first item in the array is an empty string
$urls[] = 'http://'. $testurl;
}
print_r($urls);
You asked for a regex solution, so here you go...
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
preg_match_all('/(http:\/\/.+?\.jpg)/',$test,$matches);
print_r($matches[0]);
The expression looks for parts of the string the start with http:// and end with .jpg, with anything in between. This splits your string exactly as requested.
output:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jpg
[1] => http://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)
you can split them if they are always like this vith substr() function reference: http://php.net/manual/en/function.substr.php but if they are dynamic in lenght. you need to get a ; or any other sign that is not likely to be used there before 2nd "http://" and then use explode function reference: http://php.net/manual/en/function.explode.php
$string = "http://something.com/;http://something2.com"; $a = explode(";",$string);
Try the following:
<?php
$temp = explode('http://', $test);
foreach($temp as $url) {
$urls[] = 'http://' . $url;
}
print_r($urls);
?>
$test = 'http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jp';
array_slice(
array_map(
function($item) { return "http://" . $item;},
explode("http://", $test)),
1);
For answering this question by regular expression I think you want something like this:
$test = "http://localhost/biochem/wp-content/uploads//godzilla-article2.jpghttp://localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg";
$keywords = preg_split("/.http:\/\//",$test);
print_r($keywords);
It returns exactly something you need:
Array
(
[0] => http://localhost/biochem/wp-content/uploads//godzilla-article2.jp
[1] => localhost/biochem/wp-content/uploads/life-goes-on-wpcf_300x111.jpg
)

php preg_match tab separated

I need a regular expression to look for the first N chars on an array until a tab or comma separation is found.
array look like:
array (
0 => '001,Foo,Bar',
1 => '0003,Foo,Bar',
2 => '3000,Foo,Bar',
3 => '3333433,Foo,Bar',
)
I'm looking for the first N chars, so for instance, pattern to search is 0003, get array index 1...
What would be a good way of doing this?
/^(.*?)[,\t]/
?
Try the regular expression /^0003,/ together with preg_grep:
$array = array('001,Foo,Bar', '0003,Foo,Bar', '3000,Foo,Bar', '3333433,Foo,Bar');
$matches = preg_grep('/^0003,/', $array);
var_dump($matches);
A REGEXP replacement would be: strpos() and substr()
Following your edit:
Use trim(), after searching for a comma with strpos() and retrieving the required string with substr().
use preg_split on the string
$length=10;
foreach($arr as $string) {
list($until_tab,$rest)=preg_split("/[\t,]+/", $string);
$match=substr($until_tab, $length);
echo $match;
}
or
array_walk($arr, create_function('&$v', 'list($v,$rest) = preg_split("/[\t,]+/", $string);'); //syntax not checked
This PHP5 code will do a prefix search on the first element, expecting a trailing comma. It's O(n), linear, inefficient, slow, etc. You'll need a better data structure if you want better search speed.
<?php
function searchPrefix(array $a, $needle) {
$expression = '/^' . quotemeta($needle) . ',/';
$results = array();
foreach ($a as $k => $v)
if (preg_match($expression, $v)) $results[] = $k;
return $results;
}
print_r(searchPrefix($a, '0003'));
$pattern = '/^[0-9]/siU';
for($i=0;$i<count($yourarray);$i++)
{
$ids = $yourarray[$i];
if(preg_match($pattern,$ids))
{
$results[$i] = $yourarray[$i];
}
}
print_r($results);
this will print
0 => '001',
1 => '0003',
2 => '3000',
3 => '3333433'

Categories