Replace last element string after looking the string in php - php

How do I replace the last string after i have loop on each string?
I was able to do this but still not complete
// here my get string ?dir=hello1/hello2/hello3
if (isset($_GET['dir'])) {
$hrefTabs = $_GET['dir'];
if (!empty($hrefTabs)) {
$arrayOfhref = explode('/', $hrefTabs);//I explode string /
foreach ($arrayOfhref as $roothrefline) {
$trimstrhref = preg_replace('/\s+/', '', $roothrefline); // Here i trim white space
$mmhref = ''.$roothrefline.' / '; // Here i assign each strin hyper reference
$toreplace = $roothrefline . ' / ';
$lastobj = substr_replace($mmhref, $toreplace, strlen($mmhref)); // here i want the last element not to have hyper reference attribut
echo $lastobj; // but i get this at output
//hello1 / hello1 / hello2 / hello2 /hello3 / hello3
}
}
}
My out put look like this
hello1 / hello1 / hello2 / hello2 /hello3 / hello3
I want to have it look like this
hello1 / hello2 / hello3

Before your foreach do
$lastElement = array_pop($arrayOfHref);
and display $lastElement just after your loop.
http://php.net/manual/en/function.array-pop.php

$dir = "hello1/hello2/hello3";
if(isset($dir)){
$hrefTabs = $dir;
if(!empty($hrefTabs)){
$arrayOfhref = explode('/', $hrefTabs);//I explode string /
$i = 0;
foreach($arrayOfhref as $roothrefline) {
$trimstrhref = preg_replace('/\s+/', '', $roothrefline); // Here i trim white space
$mmhref = ''.$roothrefline.' / '; // Here i assign each strin hyper reference
$toreplace = $roothrefline . ' / ';
if(++$i === count($arrayOfhref)){
echo $roothrefline;
} else {
echo $mmhref;
}
}
}
}
Something like this...

Related

How to concatenate string continuously in php?

<?php
$test = ' /clothing/men/tees';
$req_url = explode('/', $test);
$c = count($req_url);
$ex_url = 'http://www.test.com/';
for($i=1; $c > $i; $i++){
echo '/'.'<a href="'.$ex_url.'/'.$req_url[$i].'">
<span>'.ucfirst($req_url[$i]).'</span>
</a>';
//echo '<br/>'.$ex_url;....//last line
}
?>
OUTPUT - 1 //when comment last line
/ Clothing / Men / Tees
OUTPUT - 2 //when un-comment last line $ex_url shows
/ Clothing
http://www.test.com// Men
http://www.test.com// Tees
http://www.test.com/
1. Required output -
In span - / Clothing / Men / Tees and last element should not be clickable
and link should created in this way
http://www.test.com/clothing/Men/tees -- when click on Tees
http://www.test.com/clothing/Men -- when click on Men
...respectively
2. OUTPUT 2 why it comes like that
Try this:
<?php
$test = '/clothing/men/tees';
$url = 'http://www.test.com';
foreach(preg_split('!/!', $test, -1, PREG_SPLIT_NO_EMPTY) as $e) {
$url .= '/'.$e;
echo '/<span>'.ucfirst($e).'</span>';
}
?>
Output:
/Clothing/Men/Tees
HTML output:
/<span>Clothing</span>/<span>Men</span>/<span>Tees</span>
Try using foreach() to iterate the array and you'll have to keep track of the path after the url. Try it like so (tested and working code):
<?php
$test = '/clothing/men/tees';
$ex_url = 'http://www.test.com';
$items = explode('/', $test);
array_shift($items);
$path = '';
foreach($items as $item) {
$path .= '/' . $item;
echo '/ <span>' . ucfirst($item) . '</span>';
}
Try this.
<?php
$test = '/clothing/men/tees';
$req_url = explode('/', ltrim($test, '/'));
$ex_url = 'http://www.test.com/';
$stack = array();
$reuslt = array_map(function($part) use($ex_url, &$stack) {
$stack[] = $part;
return sprintf('%s', $ex_url, implode('/', $stack), ucfirst($part));
}, $req_url);
print_r($reuslt);
<?php
$sTest= '/clothing/men/tees';
$aUri= explode( '/', $sTest );
$sBase= 'http://www.test.com'; // No trailing slash
$sPath= $sBase; // Will grow per loop iteration
foreach( $aUri as $sDir ) {
$sPath.= '/'. $sDir;
echo ' / '. ucfirst( $sDir ). ''; // Unnecessary <span>
}
?>

Extract specific word from a string

It might seem easy to do but I have trouble extracting this string. I have a string that has # tags in it and I'm trying to pull the tags maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa
And here is what I want to extract 33.536759,-7.613825,17z :
$var = preg_match_all("/#(\w*)/",$path,$query);
Any way I can do this? Much appreciated.
Change your regex to this one: /#([\w\d\.\,-]*)/.
This will return the string beginning with #.
$string = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
$string = explode('/',$string);
//$coordinates = substr($string[3], 1);
//print_r($coordinates);
foreach ($string as $substring) {
if (substr( $substring, 0, 1 ) === "#") {
$coordinates = $substring;
}
}
echo $coordinates;
This is working for me:
$path = "maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa";
$var = preg_match_all("/#([^\/]+)/",$path,$query);
print $query[1][0];
A regex would do.
/#(-*\d+\.\d+),(-*\d\.\d+,\d+z*)/
If there is only one # and the string ends with / you can use the following code:
//String
$string = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
//Save string after the first #
$coordinates = strstr($string, '#');
//Remove #
$coordinates = str_replace('#', '', $coordinates);
//Separate string on every /
$coordinates = explode('/', $coordinates );
//Save first part
$coordinates = $coordinates[0];
//Do what you want
echo $coordinates;
do like this
$re = '/#((.*?),-(.*?),)/mi';
$str = 'maps/place/Residences+Jardins+de+Majorelle/#33.536759,-7.613825,17z/data=!3m1!4b1!4m2!3m1!1s0xda62d6053931323:0x2f978f4d1aabb1aa';
preg_match_all($re, $str, $matches);
echo $matches[2][0].'<br>';
echo $matches[3][0];
output
33.536759
7.613825

parsing .srt files

1
00:00:00,074 --> 00:00:02,564
Previously on Breaking Bad...
2
00:00:02,663 --> 00:00:04,393
Words...
i need to parse srt files with php and print the all subs in the file with variables.
i couldn't find the right reg exps. when doing this i need to take the id, time and the subtitle variables. and when printing there musn't be no array() s or etc. must print just the same as in the orginal file.
i mean i must print like;
$number <br> (e.g. 1)
$time <br> (e.g. 00:00:00,074 --> 00:00:02,564)
$subtitle <br> (e.g. Previously on Breaking Bad...)
by the way i have this code. but it doesn't see the lines. it must be edited but how?
$srt_file = file('test.srt',FILE_IGNORE_NEW_LINES);
$regex = "/^(\d)+ ([\d]+:[\d]+:[\d]+,[\d]+) --> ([\d]+:[\d]+:[\d]+,[\d]+) (\w.+)/";
foreach($srt_file as $srt){
preg_match($regex,$srt,$srt_lines);
print_r($srt_lines);
echo '<br />';
}
Here is a short and simple state machine for parsing the SRT file line by line:
define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME', 1);
define('SRT_STATE_TEXT', 2);
define('SRT_STATE_BLANK', 3);
$lines = file('test.srt');
$subs = array();
$state = SRT_STATE_SUBNUMBER;
$subNum = 0;
$subText = '';
$subTime = '';
foreach($lines as $line) {
switch($state) {
case SRT_STATE_SUBNUMBER:
$subNum = trim($line);
$state = SRT_STATE_TIME;
break;
case SRT_STATE_TIME:
$subTime = trim($line);
$state = SRT_STATE_TEXT;
break;
case SRT_STATE_TEXT:
if (trim($line) == '') {
$sub = new stdClass;
$sub->number = $subNum;
list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
$sub->text = $subText;
$subText = '';
$state = SRT_STATE_SUBNUMBER;
$subs[] = $sub;
} else {
$subText .= $line;
}
break;
}
}
if ($state == SRT_STATE_TEXT) {
// if file was missing the trailing newlines, we'll be in this
// state here. Append the last read text and add the last sub.
$sub->text = $subText;
$subs[] = $sub;
}
print_r($subs);
Result:
Array
(
[0] => stdClass Object
(
[number] => 1
[stopTime] => 00:00:24,400
[startTime] => 00:00:20,000
[text] => Altocumulus clouds occur between six thousand
)
[1] => stdClass Object
(
[number] => 2
[stopTime] => 00:00:27,800
[startTime] => 00:00:24,600
[text] => and twenty thousand feet above ground level.
)
)
You can then loop over the array of subs or access them by array offset:
echo $subs[0]->number . ' says ' . $subs[0]->text . "\n";
To show all subs by looping over each one and displaying it:
foreach($subs as $sub) {
echo $sub->number . ' begins at ' . $sub->startTime .
' and ends at ' . $sub->stopTime . '. The text is: <br /><pre>' .
$sub->text . "</pre><br />\n";
}
Further reading: SubRip Text File Format
Group the file() array into chunks of 4 using array_chunk(), then omit the last entry, since it's a blank line like this:
foreach( array_chunk( file( 'test.srt'), 4) as $entry) {
list( $number, $time, $subtitle) = $entry;
echo $number . '<br />';
echo $time . '<br />';
echo $subtitle . '<br />';
}
That is not going to match because your $srt_file array might look like this:
Array
([0] => '1',
[1] => '00:00:00,074 --> 00:00:02,564',
[2] => 'Previously on Breaking Bad...'.
[3] => '',
[4] => '2',
...
)
Your regex isn't going to match any of those elements.
If your intent is to read the entire file into one long memory-hog-of-a-string then use file_get_contents to get the entire file contents into one string. then use a preg_match_all to get all the regex matches.
Otherwise you might try to loop through the array and try to match various regex patterns to determine if the line is an id, a time range, or text and do thing appropriately. obviously you might also want some logic to make sure you are getting values in the right order (id, then time range, then text).
I made a class to convert a .srt file to array.
Each entry of the array has the following properties:
id: a number representing the id of the subtitle (2)
start: float, the start time in seconds (24.443)
end: float, the end time in seconds (27.647)
startString: the start time in human readable format (00:00:24.443)
endString: the end time in human readable format (00:00:24.647)
duration: the duration of the subtitle, in ms (3204)
text: the text of the subtitle (the Peacocks ruled over Gongmen City.)
The code is php7:
<?php
namespace VideoSubtitles\Srt;
class SrtToArrayTool
{
public static function getArrayByFile(string $file): array
{
$ret = [];
$gen = function ($filename) {
$file = fopen($filename, 'r');
while (($line = fgets($file)) !== false) {
yield rtrim($line);
}
fclose($file);
};
$c = 0;
$item = [];
$text = '';
$n = 0;
foreach ($gen($file) as $line) {
if ('' !== $line) {
if (0 === $n) {
$item['id'] = $line;
$n++;
}
elseif (1 === $n) {
$p = explode('-->', $line);
$start = str_replace(',', '.', trim($p[0]));
$end = str_replace(',', '.', trim($p[1]));
$startTime = self::toMilliSeconds(str_replace('.', ':', $start));
$endTime = self::toMilliSeconds(str_replace('.', ':', $end));
$item['start'] = $startTime / 1000;
$item['end'] = $endTime / 1000;
$item['startString'] = $start;
$item['endString'] = $end;
$item['duration'] = $endTime - $startTime;
$n++;
}
else {
if ($n >= 2) {
if ('' !== $text) {
$text .= PHP_EOL;
}
$text .= $line;
}
}
}
else {
if (0 !== $n) {
$item['text'] = $text;
$ret[] = $item;
$text = '';
$n = 0;
}
}
$c++;
}
return $ret;
}
private static function toMilliSeconds(string $duration): int
{
$p = explode(':', $duration);
return (int)$p[0] * 3600000 + (int)$p[1] * 60000 + (int)$p[2] * 1000 + (int)$p[3];
}
}
Or check it out here: https://github.com/lingtalfi/VideoSubtitles
You can use this project: https://github.com/captioning/captioning
Sample code:
<?php
require_once __DIR__.'/../vendor/autoload.php';
use Captioning\Format\SubripFile;
try {
$file = new SubripFile('your_file.srt');
foreach ($file->getCues() as $line) {
echo 'start: ' . $line->getStart() . "<br />\n";
echo 'stop: ' . $line->getStop() . "<br />\n";
echo 'startMS: ' . $line->getStartMS() . "<br />\n";
echo 'stopMS: ' . $line->getStopMS() . "<br />\n";
echo 'text: ' . $line->getText() . "<br />\n";
echo "=====================<br />\n";
}
} catch(Exception $e) {
echo "Error: ".$e->getMessage()."\n";
}
Sample output:
> php index.php
start: 00:01:48,387<br />
stop: 00:01:53,269<br />
startMS: 108387<br />
stopMS: 113269<br />
text: ┘ç┘à╪د┘ç┘┌»█î ╪▓█î╪▒┘┘ê█î╪│ ╪ذ╪د ┌ر█î┘█î╪ز ╪ذ┘┘ê╪▒█î ┘ê ┌ر╪»┌ر x265
=====================<br />
start: 00:02:09,360<br />
stop: 00:02:12,021<br />
startMS: 129360<br />
stopMS: 132021<br />
text: .┘à╪د ┘╪ذ╪د┘è╪» ╪ز┘┘ç╪د┘è┘è ╪د┘è┘╪ش╪د ╪ذ╪د╪┤┘è┘à -
┌╪▒╪د ╪ا<br />
=====================<br />
start: 00:02:12,022<br />
stop: 00:02:14,725<br />
startMS: 132022<br />
stopMS: 134725<br />
text: ..╪د┌»┘ç ┘╛╪»╪▒╪ز -
.╪د┘ê┘ ┘ç┘è┌┘ê┘é╪ز ┘à╪ز┘ê╪ش┘ç ╪▒┘╪ز┘┘à┘ê┘ ┘┘à┘è╪┤┘ç -<br />
=====================<br />
it can be done by using php line-break.
I could do it successfully
let me show my code
$srt=preg_split("/\\r\\n\\r\\n/",trim($movie->SRT));
$result[$i]['IMDBID']=$movie->IMDBID;
$result[$i]['TMDBID']=$movie->TMDBID;
here $movie->SRT is the subtitle of having format u posted in this question.
as we see, each time space is two new line,
hope u getting answer.
Simple, natural, trivial solution
srt subs look like this, and are separated by two newlines:
3
00:00:07,350 --> 00:00:09,780
The ability to destroy a planet is
nothing next to the power of the force
Obviously you want to parse the time, using dateFormat.parse which already exists in Java, so it is instant.
class Sub {
float start;
String text;
Sub(String block) {
this.start = null; this.text = null;
String[] lines = block.split("\n");
if (lines.length < 3) { return; }
String timey = lines[1].replaceAll(" .+$", "");
try {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss,SSS");
Date zero = dateFormat.parse("00:00:00,000");
Date date = dateFormat.parse(timey);
this.start = (float)(date.getTime() - zero.getTime()) / 1000f;
} catch (ParseException e) {
e.printStackTrace();
}
this.text = TextUtils.join(" ", Arrays.copyOfRange(lines, 2, lines.length) );
}
}
Obviously, to get all the subs in the file
List<Sub> subs = new ArrayList<>();
String[] tt = fileText.split("\n\n");
for (String s:tt) { subs.add(new Sub(s)); }

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

Extract 2 sets of numbers from a string using PHP's preg?

Here's some PHP code:
$myText = 'ABC #12345 (2009) XYZ';
$myNum1 = null;
$myNum2 = null;
How do I add the first set of numbers from $myText after the # in to $myNum1 and the second numbers from $myText that are in between the () in to $myNum2. How would I do that?
preg_match('/#(\d+).*\((\d+)\)/', $myText, $matches);
$myNum1 = $matches[1];
$myNum2 = $matches[2];
assuming you have something like:
" stuff ... #123123 stuff (456456)"
that will give you
$myNum1 = 123123
$myNum2 = 456456
If you have an input string of form "123#456", you can do
$tempArray = explode("#", $input);
if (sizeof($tempArray) != 2) {
echo "OH NO! Something bad happened!";
}
$value1 = intval($tempArray[0]);
$value2 = intval($tempArray[1]);
echo "Result: " . ($value1 + $value2);

Categories