Split string using regular expression in php - 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
)

Related

(PHP) Replace string of array elements using regex

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:

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 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 how to get a string in a specific place

I have this string
http://myipaddress:myport/mycompanyname/morethings?lovelyparameter
I want to take the word mycompanyname
any help?
I tried this:
$indexName = preg_match("http://p+:p+/","http://myipaddress:myport/mycompanyname/morethings?lovelyparameter" );
but I got this error:
preg_match(): Delimiter must not be alphanumeric or backslash
In case you don't want the preg functions, and something else from the url, you can use parse_url(). It would look like this:
$a = 'http://myipaddress:8080/mycompanyname/morethings?lovelyparameter';
$b = parse_url($a);
print_r($b);
Output:
Array
(
[scheme] => http
[host] => myipaddress
[port] => 8080
[path] => /mycompanyname/morethings
[query] => lovelyparameter
)
That way, just use something like:
$path = $b['path'];
$foo = explode('/', $path)[1];
echo $foo;
Output:
mycompanyname
Side notes:
This code won't check for malformed url, so you should do some check of your own.
If you test the url with a port number as string (as you have in the question), it won't work.
It could be done in one line:
$url = 'http://myipaddress:8080/mycompanyname/morethings?lovelyparameter';
echo explode('/', parse_url($url, PHP_URL_PATH))[1];
Output:
mycompanyname
You can use explode as
$abc = 'http://myipaddress:myport/mycompanyname/morethings?lovelyparameter';
$a = explode('/', $abc);
echo '<pre>';
print_r($a[3]);
echo '</pre>';
The explode breaks the strings into parts and returns an array of strings so you can check in array too for mycompanyname..
For the records, you were missing appropriate delimiters. A regex solution would be:
https?://.+?/(?P<company>[^/]+)/
In PHP this would be:
$regex = '~https?://.+?/(?P<company>[^/]+)/~';
$url = 'http://myipaddress:8080/mycompanyname/morethings?lovelyparameter';
preg_match($regex, $url, $match);
echo $match["company"];
// mycompanyname

How to extract parts using regular expression in PHP?

For example you have the following string:
$text = "word1:text1#atpart/foo/do/myfood$textfinal";
The function will work like:
$parts = array();
extract( $regular_exp, $text, $parts );
In the parts array we will get this:
$parts[0] = "word1";
$parts[1] = "text1";
$parts[2] = "atpart";
$parts[3] = "/foo/do/myfood";
$parts[4] = "textfinal";
Thanks!
This may not be what you are after, but the format you show looks almost like a URL with a username:password#domain authentication in front. If you can get the last $ to be served as a ?, it might be an idea to use parse_url() to parse it.
$string = "word1:text1#atpart/foo/do/myfood?textfinal"; // notice the ?
$string = "none://".$string; // We need to add a protocol for this to work
print_r (parse_url($string));
Result:
Array (
[scheme] => none
[host] => atpart
[user] => word1
[pass] => text1
[path] => /foo/do/myfood
[query] => textfinal )
the advantage of this would be that it's pretty flexible if one or more parts can be missing in the incoming data. If that's not an issue, a regex may be more convenient.
try
$parts = preg_split('/[:#\$]+/', $text);
Without more details, this matches the proposed example:
preg_match('#(.*?):(.*?)#(.*?)(/.*?)\$(.*)#', $text, $parts);
note that you will get the parts starting at index 1 instead of 0.
$delims=':#$';
$word = strtok('word1:text1#atpart/foo/do/myfood$textfinal',$delims);
while ( $word!==false ) {
foreach( explode('/',$word,2) as $tmp){
$words[]=$tmp;
}
$word = strtok($delims);
}
var_dump($words);
On one hand this is probably overkill. On the other hand, this may be more flexible depending on how different the string can be.
Demo: http://codepad.org/vy5b9yX7
Docs: http://php.net/strtok

Categories