How to separate mp3, mp4 file name from string using php? - php

Hi anyone can help I want separate mp3, mp4 from imploded data in PHP
my data string
$data = "song1.mp3, video1.mp4, song2.mp3"
i want to divide into two separate strings 1 string contains only mp4 with (,) separated and another with mp3
my data from database:
$data = "song1.mp3, video.mp4, song2.mp3";
$mp4 = video1.mp4,video2.mp4,..etc;
$mp3 = song1.mp3,song2.mp3,..etc;
thank you

Assuming your songs names are well formatted, meaning that they are named as title.suffix
<?php
$data = "song1.mp3, video.mp4, song2.mp3";
$mp3 = [];
$mp4 = [];
$song_names = explode(',', $data);
foreach ($song_names as $song_name) {
$song_name = trim($song_name);
$parts = explode('.', $song_name);
if (count($parts) == 2) {
$suffix = $parts[1];
if ($suffix == 'mp3') {
$mp3[] = $song_name;
} else if ($suffix == 'mp4') {
$mp4[] = $song_name;
}
}
}
//using implode so that we won't have an extra comma hanging in the end
$mp4 = implode(', ', $mp4);
$mp3 = implode(', ', $mp3);
?>

Use explode() to converting string to array by , delimiter. Then loop through array items and get extension of file name using substr() and check it.
$data = "song1.mp3, video1.mp4, song2.mp3";
$mp4 = $mp3 = "";
foreach (explode(",", $data) as $file){
$file = trim($file);
substr($file, -3) == "mp4" ? $mp4.=$file."," : $mp3.=$file.",";
}
$mp4 = substr($mp4, 0, -1);
$mp3 = substr($mp3, 0, -1);
Check result in demo

This sounds like a job for a preg_match_all() regex:
<?php
$string = 'song1.mp3, video.mp4, song2.mp3';
$regex = '#([^,\s]+\.mp3)#';
preg_match_all($regex, $string, $mp3s);
$regex = '#([^,\s]+\.mp4)#';
preg_match_all($regex, $string, $mp4s);
var_dump($mp3s[0]);
var_dump($mp4s[0]);
Which gives you:
array(2) { [0]=> string(9) "song1.mp3" [1]=> string(9) "song2.mp3" }
array(1) { [0]=> string(9) "video.mp4" }
Here's the code in action https://3v4l.org/2EmkR
Here's the docs for preg_match_all() http://php.net/manual/en/function.preg-match-all.php

Ok - a slightly different approach using pathinfo
$data = 'song1.mp3, video1.mp4, song2.mp3';
$mp3s = [];
$mp4s = [];
foreach (explode(', ', $data) as $file) {
$type = pathinfo($file)['extension'];
$type === 'mp3' ? $mp3s[] = $file : $mp4s[] = $file;
}
echo implode(', ', $mp4s) . PHP_EOL;
echo implode(', ', $mp3s) . PHP_EOL;
Could definitely use some validation and so forth but as an MVP it does the trick.

Related

How to fix url contains arabic characters

I want to get the url of each file in certain directory
i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.
example:
this is my code output:
String A :
https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3
this code is not working in some android devices
but the next code works with all devices
String B:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
Note: i got String B from internet download manager that converts it automatically when i tried to use string A
my question is:
how to convert String A to String B by php
and is there better way to readdir and get the url of each file
My code is:
if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
//...
} else { //create object with two fields
sort($file);
$fileName = pathinfo($file)['filename'];
if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}
Try this one, I've used once for a legacy project:
function encode_fullurl($url) {
$output = '';
$valid = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*\'();:#&=+$,/?#[]%';
$length = strlen($url);
for ($i = 0; $i < $length; $i++) {
$character = $url[$i];
$output .= (strpos($valid, $character) === false ? rawurlencode($character) : $character);
}
return $output;
}
$url ="https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3";
echo encode_fullurl($url);
output:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
it is not very performing, but it should do what you need
this code worked for me
thanks every one
$res1 = "https://linkimage2url.com" .$path."/".$file;
$query = flash_encode ($res1);
$url = htmlentities($query);
function flash_encode($string)
{
$string = rawurlencode($string);
$string = str_replace("%2F", "/", $string);
$string = str_replace("%3A", ":", $string);
return $string;
}

Match variable value with text file row wise

I want to match variable value with text file rows, for example
$brands = 'Applica';
and text file content like -
'applica' = 'Applica','Black and Decker','George Foreman'
'black and decker' = 'Black and Decker','Applica'
'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'
'bosch' = 'Bosch','Thermador'
As there are four rows in text file.
and first word of each row is brand which is compatible with their equal to brands.
like applica is compatible with 'Applica' and 'Black and Decker' and 'George Foreman'
I want to match variable $brands with word applica and if it matches then store their equal to value like 'Applica','Black and Decker','George Foreman' in new variable.
Please provide some guidance.
Thanks.
Update -
<?php
$brands = "brands.txt";
$contents = file_get_contents($brands);
$brandsfields = explode(',', $contents);
$csvbrand = 'applica';
foreach($brandsfields as $brand) {
$newname = substr($brand,1,-1);
echo $newname . "\t";
}
?>
This should work
$matches = explode("\n", "'applica' = 'Applica','Black and Decker','George Foreman'\n'black and decker' = 'Black and Decker','Applica'\n'amana' = 'Amana','Whirlpool','Roper','Maytag','Kenmore','Kitchenaid','Jennair'\n'bosch' = 'Bosch','Thermador'");
$brand = "applica";
$equalValues = [];
foreach ($matches as $key => $value) {
$keyMatch = str_replace("'", "", trim(explode('=', $value)[0]));
$valuesMatch = explode('=', $value)[1];
$escapedDelimiter = preg_quote("'", '/');
preg_match_all('/' . "'" . '(.*?)' . "'" . '/s', $valuesMatch, $matches);
if ($brand == $keyMatch) {
$equalValues = $matches[1];
}
}
var_dump($equalValues);
if brand is equal to applica $equalvalues shoud be equal to :
array(3) {
[0]=>
string(7) "Applica"
[1]=>
string(16) "Black and Decker"
[2]=>
string(14) "George Foreman"
}
preg_match_all("/'" . $csvbrand ."' = (.*)/", $contents, $output_array);
$names = explode(",", str_replace("'", "", $output_array[1][0]));
Var_dump($names); // results in ->
//Applica
//Black and Decker
//George Foreman

How to remove string with comma in a big string?

I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");

preg_replace is modifying JavaScript

I have a template tool, that replaces placeholders one of the pieces of the tool loads other files, here is what I am using for debugging:
var_dump($string);
$tmp = preg_replace('/\\$import\(("|\')' . $f . '("|\')\).*;/i', $string, $tmp);
var_dump($tmp);
The first var_dump prints out the contents of a file, and in the file there is this line of JavaScript:
$("#image-menu .info").html(text.replace(/(.+?:)/, "<b>$1</b>"));
After the pre_replace I have the second var_dump which then prints out this:
$("#image-menu .info").html(text.replace(/(.+?:)/, "<b>"</b>"));
As you can see $1 was replaced by a ", and I am not sure why. Any ideas as to why it is getting replaced?
Here is the full method:
private function loadIncludes(){
$tmp = $this->template;
$matches = array();
preg_match_all('/(\\$import\(("|\')(.+?)("|\')\).*;)/i', $tmp, $matches);
$files = $matches[3];
$replace = 0;
foreach($files as $key => $file){
$command = preg_replace("/\\\$import\((\"|').+?(\"|')\)/", "", $matches[0][$key]);
$string = $this->import($file);
$string = $this->runFunctions($string, "blah" . $command);
$f = preg_quote($file, "/");
var_dump($string);
$tmp = preg_replace('/\\$import\(("|\')' . $f . '("|\')\).*;/i', $string, $tmp);
var_dump($tmp);
$replace++;
}
$this->template = $tmp;
if($replace > 0){
$this->loadIncludes();
}
}
Within single quotes you can't use control characters like \r or \n, meaning you don't have to double-escape your $. Your \\$ can simply be \$.

Function for each subfolder in PHP

I am new in PHP and can't figure out how to do this:
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$domain_and_slash = http://www.domainname.com . '/';
$address_without_site_url = str_replace($domain_and_slash, '', $link);
foreach ($folder_adress) {
// function here for example
echo $folder_adress;
}
I can't figure out how to get the $folder_adress.
In the case above I want the function to echo these four:
folder1
folder1/folder2
folder1/folder2/folder3
folder1/folder2/folder3/folder4
The $link will have different amount of subfolders...
This gets you there. Some things you might explore more: explode, parse_url, trim. Taking a look at the docs of there functions gets you a better understanding how to handle url's and how the code below works.
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$parts = parse_url($link);
$pathParts = explode('/', trim($parts['path'], '/'));
$buffer = "";
foreach ($pathParts as $part) {
$buffer .= $part.'/';
echo $buffer . PHP_EOL;
}
/*
Output:
folder1/
folder1/folder2/
folder1/folder2/folder3/
folder1/folder2/folder3/folder4/
*/
You should have a look on explode() function
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of
which is a substring of string formed
by splitting it on boundaries formed
by the string delimiter.
Use / as the delimiter.
This is what you are looking for:
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$domain_and_slash = 'http://www.domainname.com' . '/';
$address_without_site_url = str_replace($domain_and_slash, '', $link);
// this splits the string into an array
$address_without_site_url_array = explode('/', $address_without_site_url);
$folder_adress = '';
// now we loop through the array we have and append each item to the string $folder_adress
foreach ($address_without_site_url_array as $item) {
// function here for example
$folder_adress .= $item.'/';
echo $folder_adress;
}
Hope that helps.
Try this:
$parts = explode("/", "folder1/folder2/folder3/folder4");
$base = "";
for($i=0;$i<count($parts);$i++){
$base .= ($base ? "/" : "") . $parts[$i];
echo $base . "<br/>";
}
I would use preg_match() for regular expression method:
$m = preg_match('%http://([.+?])/([.+?])/([.+?])/([.+?])/([.+?])/?%',$link)
// $m[1]: domain.ext
// $m[2]: folder1
// $m[3]: folder2
// $m[4]: folder3
// $m[5]: folder4
1) List approach: use split to get an array of folders, then concatenate them in a loop.
2) String approach: use strpos with an offset parameter which changes from 0 to 1 + last position where a slash was found, then use substr to extract the part of the folder string.
EDIT:
<?php
$folders = 'folder1/folder2/folder3/folder4';
function fn($folder) {
echo $folder, "\n";
}
echo "\narray approach\n";
$folder_array = split('/', $folders);
foreach ($folder_array as $folder) {
if ($result != '')
$result .= '/';
$result .= $folder;
fn($result);
}
echo "\nstring approach\n";
$pos = 0;
while ($pos = strpos($folders, '/', $pos)) {
fn(substr($folders, 0, $pos++));
}
fn($folders);
?>
If I had time, I could do a cleaner job. But this works and gets across come ideas: http://codepad.org/ITJVCccT
Use parse_url, trim, explode, array_pop, and implode

Categories