I have issue with preg_replace function in PHP. I cant figure out a pattern and a replacement.
I have this two strings and some code:
$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';
$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);
$dirname1 = end($pieces1); // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php
$output = preg_replace($pattern, $replacement, $dirname1); // or (..,..,$dirname2
echo $output; // i need 1min(without period_) or abcdrfg (without .php)
UPD:
function Cat($dirname)
{
$name = explode('/', $dirname);
$pattern = ???;
$replacement = ???;
return preg_replace($pattern, $replacement, $dirname1);
}
print(Cat('hdadas/dasdad/dasd/period_1min'))); // output need 1min only
print(Cat('hdadas/dasdad/dasd/period_1min/abcdrfg.php'))); // output need abcdrfg only
This should work for you:
(Here I use basename() to get only the last part of the path, then I use pathinfo() to get the last part without the extension. After this I just use preg_replace() to replace everything before the underscore with an empty string)
<?php
$dirname1 = "hdadas/dasdad/dasd/period_1min";
$dirname2 = "hdadas/dasdad/dasd/period_1min/abcdrfg.php";
$dirname1 = pathinfo(basename($dirname1))["filename"];
$dirname2 = pathinfo(basename($dirname2))["filename"];
echo $output = preg_replace("/(.*)_/", "", $dirname1);
?>
output:
1min
abcdrfg
How about this regex /^.+_|\.[^.]+$/:
$dirname1 = 'hdadas/dasdad/dasd/period_1min';
$dirname2 = 'hdadas/dasdad/dasd/period_1min/abcdrfg.php';
$pieces1 = explode('/', $dirname1);
$pieces2 = explode('/', $dirname2);
$dirname1 = end($pieces1); // output will be period_1min
$dirname2 = end($pieces2); // output will be abcdrfg.php
$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname1); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)
$output = preg_replace('/^.+_|\.[^.]+$/', '', $dirname2); // or (..,..,$dirname2
echo $output,"\n"; // i need 1min(without period_) or abcdrfg (without .php)
Output:
1min
abcdrfg
Related
Trying to add HTML tags around the first word in each new line in WooCommerce short description and validate that the file exist. If it exist it will output a link.
I tried this:
$string = $short_description;
$keys = array('a1', 'a2', 'a3');
$patterns = array();
foreach($keys as $key)
$patterns[] = '/\b('.$key.')\b/i';
echo preg_replace($patterns, '$0', $string);
$url = preg_replace($patterns, 'https://www.example.com/media/' .$product->get_sku(). '/' .$product->get_sku(). '$0.pdf', $string);
$handle = #fopen($url,'r');
if($handle !== false){ ?>
<?php echo preg_replace($patterns, '<li>$0</li>', $string);?>
<?php } else {?>
<?php echo preg_replace($patterns, '<li>$0</li>', $string);?>
This is as close I could get, the limitation is that you need to add all words that needs to be changed (will be total 200+) and also the validation $url is not working as it echos the $string aswell.
So how can I either get the $url correct or is there a better way to wrap html tags to the first word on each new line?
Got it working with:
$s = strip_tags($short_description, '<br>');
$rows = explode( "\n", $s );
foreach( $rows as $r ){
echo preg_replace('/^([^ ]*)/', '$1', $r);
}
and then with
if is_readable
to output link or not
I have a url that will always look like some variation of this
https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg
I need to remove with PHP the resolution specifier "-150x150" so that it reads
https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg
If it's always -150x150 you can just use str_replace():
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = str_replace('-150x150', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
If you need a way to strip out any resolution, you can use a regular expression for that:
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$stripped = preg_replace('/-[0-9]+x[0-9]+/', '', $url);
var_dump($stripped);
// string(62) "https://sitename/wp-content/uploads/2017/09/59a778097ae6e.jpeg"
hello you can use strpos() and substr() functions
<?php
$str1 = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str2 = "-150x150";
$pos = strpos($str1, $str2);
$part1 = substr($str1, $pos);
$part2 = substr($pos+1, strlen($str1));
$final_str = $part1.$part2;
echo $final_str;
?>
or you can also just use str_replace() and replace the part of the url by nothing :
<?php
$url = "https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg";
$str = "-150x150";
// will replace $str by '' in $url
$url = str_replace($str, '', $url);
echo $url;
?>
If it's not always 150x150, here's a nifty solution.
$url = 'https://sitename/wp-content/uploads/2017/09/59a778097ae6e-150x150.jpeg';
First get the extension
$ext = explode('.', $url);
$ext = $ext[count($ext)-1];
Then split by '-'
$array = explode('-', $url);
Pop the last array element which will be the resolution (150x150 here)
array_pop($array);
Then implode by '-' again and concatenate the extension to the new url
$new_url = implode('-', $array). '.' .$ext;
I have make a try like this:
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-13);
and the output work :
localhost/product/-/123456 cause this just for above link with 13 character after /-/123456
How to remove all? i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-(.*));
not work and error sintax.
and i try
$string = "localhost/product/-/123456-Ebook-Guitar";
echo $string = substr($string, 0, strpos(strrev($string), "-/(0-9+)")-999);
the output is empty..
Assume there are no number after localhost/product/-/123456, then I will just trim it with below
$string = "localhost/product/-/123456-Ebook-Guitar";
echo rtrim($string, "a..zA..Z-"); // localhost/product/-/123456
Another non-regex version, but require 5.3.0+
$str = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo dirname($str) . "/" . strstr(basename($str), "-", true); //localhost/product/-/123456
Heres a more flexibility way but involve in regex
$string = "localhost/product/-/123456-Ebook-Guitar";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
$string = "localhost/product/-/123456-Ebook-Guitar-1-pdf/";
echo preg_replace("/^([^?]*-\/\d+)([^?]*)/", "$1", $string);
// localhost/product/-/123456
This should match capture everything up to the number and remove everything afterward
regex101: localhost/product/-/123456-Ebook-Guitar
regex101: localhost/product/-/123456-Ebook-Guitar-1-pdf/
Not a one-liner, but this will do the trick:
$string = "localhost/product/-/123456-Ebook-Guitar";
// explode by "/"
$array1 = explode('/', $string);
// take the last element
$last = array_pop($array1);
// explode by "-"
$array2 = explode('-', $last);
// and finally, concatenate only what we want
$result = implode('/', $array1) . '/' . $array2[0];
// $result ---> "localhost/product/-/123456"
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
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 \$.