How to move a leading substring to the end of string? - php

How can I cut part of string before some word put on the end of the same string?
For example:
$data = '1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg,';
I want to put all before 4.jpg, at the end of string like this:
$data = '4.jpg,5.jpg,6.jpg,7.jpg,1.jpg,2.jpg,3.jpg,';

Here's something you can try.
<?php
$data = '1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg,';
$cut_name = '4.jpg'; //splice from #4
$data = explode(',', $data);
$cut_from = array_search($cut_name, $data);
array_pop($data);
$removed = array_splice($data, 0, $cut_from);
$data = implode(',', array_merge($data, $removed));
echo $data . ',';

You can use also some like this:
$data = '1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg';
function reorder_string($string,$separator){
$splited = explode($separator,$string);
//Explanations:
//$splited[0] = "1.jpg,2.jpg,3.jpg,"
//$splited[1] = "5.jpg,6.jpg,7.jpg"
//$separator = "4.jpg,"
//finally reorder
return $separator.$splited[1].",".$splited[0];
}
echo reorder_string($data,"4.jpg,");

This is too easy with this two-function, one-liner!
Code: (Demo)
$data = '1.jpg,2.jpg,3.jpg,4.jpg,5.jpg,6.jpg,7.jpg,';
$new_leader='4.jpg';
echo strstr($data,$new_leader),strstr($data,$new_leader,true);
Output:
4.jpg,5.jpg,6.jpg,7.jpg,1.jpg,2.jpg,3.jpg,
*note, can break if you change 2.jpg to 44.jpg due to unintended substring matching.

Related

multiple characters replacements in string php

Let's say that I have the following string:
$string = 'xxyyzz';
And then I have a substitution array like this:
$subs = ['xy'];
Meaning that every x should be replaced by y in my string and every y should be replaced by x. Let's say that my substitution array can only contain pairs of characters to be replaced in my $string.
How would I go about doing this?
I tried using str_replace the following way but that doesn't work:
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$reversed_sub_arr = array_reverse($sub_arr);
$output = str_replace($sub_arr, $reversed_sub_arr, str_split($string));
}
$output = implode('', $output);
But the output gives me xxxxzz
The output should be yyxxzz
Thanks for any help
This working for your case
$string = 'xxyyzz';
$subs = ['xy'];
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$output = strtr($string, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));
}
echo $output; //yyxxzz
Extending #Orgil answer if two items in $subs array like $subs = ['xy', 'dz']
$string = $output = 'xxyyzz';
$subs = ['xy', 'dz'];
foreach ($subs as $sub) {
$sub_arr = str_split($sub);
$output = strtr($output, array($sub_arr[0]=>$sub_arr[1], $sub_arr[1]=>$sub_arr[0]));
}
echo $output;
Demo

PHP truncate commas in string

in PHP, I want to change this string:
",,,3,4,,,5,6,,7,8,"
into this:
"3,4,5,6,7,8"
I've managed to strip commas at the beginning and end of the string, but this only accomplish 50% of my need:
<?php
$hello = ",,,3,4,5,6,,7,8,";
echo rtrim(ltrim($hello,","),",");
result:
"3,4,,,5,6,,7,8"
Any solution?
Do this little trick:
$hello = ",,,3,4,,,5,6,,7,8,";
$hello = implode(",",array_filter(explode(',',$hello)));
If your string is more complicated (i.e. it's a CSV which may potentially have fields wrapped in " " to escape commas you can do this:
$hello = ",,,3,4,,,5,6,,\"I,have,commas\",,7,8,";
$fields = array_filter(str_getcsv($hello));
$hello = str_putcsv($fields);
Where str_putcsv is defined in https://gist.github.com/johanmeiring/2894568 as
if (!function_exists('str_putcsv')) {
function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
$fp = fopen('php://temp', 'r+b');
fputcsv($fp, $input, $delimiter, $enclosure);
rewind($fp);
$data = rtrim(stream_get_contents($fp), "\n");
fclose($fp);
return $data;
}
}
You can use trim() and Regx to achieve this, please have a look on the below code, it may help you
$from = ",,,,,,3,4,,,5,6,,7,8,,,";
echo $from;
echo "<pre>";
$to = preg_replace('/,+/', ',', trim($from,","));
echo $to;
implode(",", array_filter(explode(",", ",,,3,4,,,5,6,,7,8,"))
That's a little bit to read, but essentially explode the string on a comma, call array_filter on the result of that, then implode it back together.

php match a string from other string

I have a string as $test = 'aa,bb,cc,dd,ee' and other string as $match='cc'. I want the result as $result='aa,bb,dd,ee'.
I am not able to get te result as desired as not sure which PHP function can give the desired output.
Also if I have a string as $test = 'aa,bb,cc,dd,ee' and other string as $match='cc'. I want the result as $match=''. i.e if $match is found in $test then $match value can be skipped
Any help will be really appreciated.
You can try with:
$test = 'aa,bb,cc,dd,ee';
$match = 'cc';
$output = trim(str_replace(',,', ',', str_replace($match, '', $test), ','));
or:
$testArr = explode(',', $test);
if(($key = array_search($match, $testArr)) !== false) {
unset($testArr[$key]);
}
$output = implode(',', $testArr);
Try with preg_replace
$test = 'aa,bb,cc,dd,ee';
$match ='cc';
echo $new = preg_replace('/'.$match.',|,'.$match.'$/', '', $test);
Output
aa,bb,dd,ee
$test = 'aa,bb,cc,dd,ee';
$match='cc';
echo trim(str_replace(',,', ',' , str_replace($match,'',$test)),',');
DEMO
Try this:
$test = 'aa,bb,cc,dd,ee';
$match = 'cc';
$temp = explode(',', $test);
unset($temp[ array_search($match, $temp) ] );
$result = implode(',', $temp);
echo $result;

how to get only the specific content from a file using PHP.

how to get only the specific content from a file using PHP.
I have a file with content:
reference 1.pdb
mobile 4r_1.pdb
ignore
fit
mobile 4r_10.pdb
ignore
fit
mobile 4r_22220.pdb
ignore
fit
Now, I want to take all the names i.e. (output)
4r_1
4r_10
4r_22220
in an array and print it.
The program i have written in php doesn't work properly, can have a look
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
if ($output4 !="/mobile/i")
{
print $output4;
print "\n";
}
Please help! to extract only the names
Try this:
$convert = explode("\n", $data); // take it in an array
$filenames = array();
foreach ($convert as $item) {
if(strstr($item,'mobile')) {
array_push($filenames,preg_replace('/mobile[\s]?([A-Za-z0-9_]*).pdb/','${1}',$item));
}
}
Now all the file names (assuming they are file names) are in the array $filenames
preg_grep returns an array of matching lines, your condition is treating $output4 as a string.
Loop over the array to print out each line and use either substr or str_replace to remove the unwanted characters from the string
$data = file_get_contents('test.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert); //take only the line starts with mobile and put it in an array
foreach($output4 as $entry) {
print str_replace("mobile ", "", $entry) . "\n";
}
Below code should work:
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
$output4 = preg_grep("/mobile/i",$convert);
if (count($output4))
{
foreach ($output as $line) {
print $line; // or substr($line, 6) to remove mobile from output
print "\n";
}
}
Note:
Instead of doing
$data = file_get_contents('file.txt'); // to read the file
$convert = explode("\n", $data); // take it in an array
You may read a file into array with file() function:
$convert = file('file.txt'); // to read the file
Try this:
$content = file_get_contents('file.txt');
$lines = explode("\n", $content);
foreach ($lines as $line) {
if (preg_match('/^mobile\s+(.+)$/', $line, $match)) {
echo $match[1], "\n";
}
}

How do I remove specific URL from user input?

I want remove some URL from user input.
Example user input
$input = 'http://www.yahoo.com/';
$input = 'http://yahoo.com/';
$input = 'www.yahoo.com';
$input = 'yahoo.com';
$input = 'http://answers.yahoo.com/question/index;_ylt=AhiI2Ax0jmujpU01wK7W4cLj1KIX;_ylv=3?qid=20110224130854AA9LGdy';
$input = 'yahoo';
$input = 'http://yahoo.com';
$input = 'I love http://yahoo.com';
output I love
Any domain with yahoo.com I want remove the output or return empty result. Maybe more than one domain. Let me know.
Try something like this:
$domains = array('yahoo.com', 'other-domain.org');
$domainsrgx = implode('|', array_map('preg_quote', $domains));
$filtered_userinput = preg_replace('#(^|\s+)(https?://)?([^/\s]*\.)?('.$domainsrgx.')(/[^\s]*)?(?=(\s|$))#is', '', $userinput);
This should remove everything from your example.
$data=str_replace('yahoo.com','',$data);
you can use an array to replace\remove multiple domains
$remove=array('yahoo.com','google.com');
$data=str_replace($remove,'',$data);
Ok. You can do
$rows = split("[\n|\r]", $input);
$output = "";
foreach($rows as $row){
if(strpos($row,"yahoo.com")){
continue;
}else{
$output = $row."\n";
}
}
I hope I'm not missing anything.

Categories