Split string with PHP piece by piece - php

I have a string that I want to split like this:
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG <--- Original string
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264 <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL.1080p <--- no match
Sinn.und.Sinnlichkeit.1995.German.DL <--- no match
Sinn.und.Sinnlichkeit.1995.German <--- no match
Sinn.und.Sinnlichkeit.1995 <--- no match
Sinn.und.Sinnlichkeit <--- match
Sinn.und <--- no match
Sinn <--- no match
Until it has a API match.
Can you help me with that? I tried with preg_split, but it's not really working...
$string = 'Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG';
$split = preg_split('/[.-]/', $string);
foreach( $split AS $explode )
{
echo $explode;
}

You're splitting correct. All it takes is a for loop, building the required $arr from the parts as you go along.
$string = 'Sinn.und.Sinnlichkeit.1995.German.DL.1080p.BluRay.x264-RSG';
$split = preg_split('/[.-]/', $string);
$arr = [];
$brr = [];
foreach( $split AS $explode)
{
$arr[] = $explode;
// check $arr or implode($arr) with api
// or push to
$brr[] = $arr;
}
$result = array_reverse($brr);

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

Encode contents between Two Special Strings

All I want is to Get contents between two strings like the following line:
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
I wish to get all contents between 81L and 82R, then encode them to Base64 automatically by Preg_match I think, I've done some ways to do it but didn't get what was expected!
Base Form:
81Lhello82R 81Lmy82R 81Lwife82R
Output:
81LaGVsbG8=82R 81LbXk=82R 81Ld2lmZQ==82R
Hard rules:
$leftMask = '81L';
$rightMask = '82R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#'.$leftMask.'(.*)'.$rightMask.'#U',$content, $out);
$output = [];
foreach($out[1] as $val){
$output[] = $leftMask.base64_encode($val).$rightMask;
}
$result = str_replace($out[0], $output, $content);
RegExp rules
$leftMask = '\d{2}L';
$rightMask = '\d{2}R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#('.$leftMask.')(.*)('.$rightMask.')#U',$content, $out);;
$output = [];
foreach($out[2] as $key=>$val){
$output[] = $out[1][$key].base64_encode($val).$out[3][$key];
}
$result = str_replace($out[0], $output, $content);
This is a job for preg_replace_callback:
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
$output = preg_replace_callback(
'/(?<=\b\d\dL)(.+?)(?=\d\dR)/',
function($matches) {
return base64_encode($matches[1]); // encode the word and return it
},
$content);
echo $output,"\n";
Where
(?<=\b\d\dL) is a positive lookbehind that makes sure we have 2 digits and the letter L before the word to encode
(?=\d\dR) is a positive lookahead that makes sure we have 2 digits and the letter R after the word to encode
(.+?) is the capture group that contains the word to encode
Output:
81LaGVsbG8=82R 81LbXk=82R 81Ld2lmZQ==82R

parsing it out text divided by a special character?

I have single field that allows the user to input different options in one string. So, 13123123|540|450
How would I parse out those three values into three variables?
You can use list to put them into three distinct variables:
$str = '13123123|540|450';
list($one, $two, $three) = explode('|', $str);
Alternatively, you can just access them via the array indicies if you wanted to:
$str = '13123123|540|450';
$split = explode('|', $str);
// $split[0] == 13123123
You can try the following methods:
$input = #$_POST["field"];
// Method 1: An array
$options = explode ("|", $input);
/*
The $options variable will now have the following:
$options[0] = "13123123";
$options[1] = "540";
$options[2] = "450";
*/
// Method 2: Assign to different variables:
list($opt1, $opt2, $opt3) = explode ("|", $input);
/*
The variables will now have the following:
$opt1 = "13123123";
$opt2 = "540";
$opt3 = "450";
*/
// Method 3: Regular expression:
preg_match ("/(\w*)|(\w*)|(\w*)/i", $string, $matches);
/*
The $options variable will now have the following:
$matches[0] = "13123123";
$matches[1] = "540";
$matches[2] = "450";
*/
Use regex based on the numbers before each |. So something along the lines of [\d{8}]^\|] for the first one and so on.

Strlen to strip every [x] characters

I'm trying strip every third character (in the example a period) below is my best guess and is close as ive gotten but im missing something, probably minor. Also would this method (if i could get it working) be better than a regex match, remove?
$arr = 'Ha.pp.yB.ir.th.da.y';
$strip = '';
for ($i = 1; $i < strlen($arr); $i += 2) {
$arr[$i] = $strip;
}
One way you can do it is:
<?php
$oldString = 'Ha.pp.yB.ir.th.da.y';
$newString = "";
for ($i = 0; $i < strlen($oldString ); $i++) // loop the length of the string
{
if (($i+1) % 3 != 0) // skip every third letter
{
$newString .= $oldString[$i]; // build up the new string
}
}
// $newString is HappyBirthday
echo $newString;
?>
Alternatively the explode() function might work, if the letter you're trying to remove is always the same one.
This might work:
echo preg_replace('/(..)./', '$1', 'Ha.pp.yB.ir.th.da.y');
To make it general purpose:
echo preg_replace('/(.{2})./', '$1', $str);
where 2 in this context means you are keeping two characters, then discarding the next.
A way of doing it:
$old = 'Ha.pp.yB.ir.th.da.y';
$arr = str_split($old); #break string into an array
#iterate over the array, but only do it over the characters which are a
#multiple of three (remember that arrays start with 0)
for ($i = 2; $i < count($arr); $i+=2) {
#remove current array item
array_splice($arr, $i, 1);
}
$new = implode($arr); #join it back
Or, with a regular expression:
$old = 'Ha.pp.yB.ir.th.da.y';
$new = preg_replace('/(..)\./', '$1', $old);
#selects any two characters followed by a dot character
#alternatively, if you know that the two characters are letters,
#change the regular expression to:
/(\w{2})\./
I'd just use array_map and a callback function. It'd look roughly like this:
function remove_third_char( $text ) {
return substr( $text, 0, 2 );
}
$text = 'Ha.pp.yB.ir.th.da.y';
$new_text = str_split( $text, 3 );
$new_text = array_map( "remove_third_char", $new_text );
// do whatever you want with new array

How do I get rid of Blank spaces?

$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$fdat = str_replace($filtr,"",$data);
$clean = implode(",",$fdat);
echo $clean;
this gives out put ,,searchengine,seo,search
How can I get rid of first two blank commas?
Better get the difference of your splitted arrays $exp minus $filtr:
$clean = implode(',', array_diff($exp, $filtr));
This will also avoid the chance that you will only remove a substring of another word like when removing car from bike,car,carpet should result in bike,carpet and not in bike,pet.
And if you want to allow whitespace before and after each word, consider using trim and preg_split:
$exp = preg_split('/\s*,\s*/', trim($data));
trim will remove any preceding and trailing whitespace and the pattern for preg_split allows whitespace surrounding the comma too.
I'm getting an error when trying this code you did. You can use the following to remove google & bing (that are in an array) from a comma separated string:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
$diff = array_diff($exp, $filtr);
$clean = implode(",",$diff);
echo $clean;
Your piece of code could also look like this:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach ($exp as $key => $item) {
if (in_array($key, $filtr)) unset($exp[$key]);
}
$clean = implode(",",$exp);
echo $clean;
Its useful when there is few items in $data. For big arrays it would need optimizing.
You would be better if checking the value within a loop like so:
$data = "google,bing,searchengine,seo,search";
$exp = explode(",",$data);
$filtr = array("google","bing");
foreach($exp as $k => $v)
{
if(in_array($v,$filtr))
{
unset($ext[$k]);
}
}
$clean = implode(",",$ext);
echo $clean;

Categories