I have this very simple url bbcoder which i wish to adjust so if the linked does not contain http:// to add it in, how can i do this?
$find = array(
"/\[url\=(.+?)\](.+?)\[\/url\]/is",
"/\[url\](.+?)\[\/url\]/is"
);
$replace = array(
"$2",
"$1"
);
$body = preg_replace($find, $replace, $body);
You can use a (http://)? to match the http:// if exists, and ignore the group result in 'replace to' pattern and use your own http:// , like this:
$find = array(
"/\[url\=(http://)?(.+?)\](.+?)\[\/url\]/is",
"/\[url\](http://)?(.+?)\[\/url\]/is"
);
$replace = array(
"$3",
"$2"
);
$body = preg_replace($find, $replace, $body);
if(strpos($string, 'http://') === FALSE) {
// add http:// to string
}
// I've added the http:// in the regex, to make it optional, but not remember it,
// than always add it in the replace
$find = array(
"/\[url\=(?:http://)(.+?)\](.+?)\[\/url\]/is",
"/\[url\](.+?)\[\/url\]/is"
);
$replace = array(
"$2",
"http://$1"
);
$body = preg_replace($find, $replace, $body);
If you would use a callback function and preg_replace_callback(), you can use something like this:
You can do that this way. It will always add 'http://', and than the string without 'http://'
$string = 'http://'. str_replace('http://', '', $string);
Related
How do I use preg_replace text/url. For example, I have a url like this: http://www.web.org/dorama/1201102144/hitoya-no-toge. I just want to show web.org. The url is not always same, for example sometimes it's: http://www.web.org/movies/123/no etc.
I only know the basics of it. Here is what I tried. It still does not delete the slash.
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$patterns = array();
$patterns[0] = '/http:/';
$patterns[1] = '/dorama/';
$patterns[2] = '/1201102144/';
$replacements = array();
$replacements[2] = '';
$replacements[1] = '';
$replacements[0] = '';
echo preg_replace($patterns, $replacements, $url);
result when i run it //www.web.org///hitoya-no-toge
For such a job, I'd use parse_url then explode:
$url = "http://www.web.org/dorama/1201102144/hitoya-no-toge";
$host = (parse_url($url))['host'];
$domain = (explode('.', $host, 2))[1];
echo $domain;
Output:
web.org
Use preg_match instead preg_replace i think http://php.net/manual/en/function.preg-match.php
// get host name from URL
preg_match('#^(?:http://)?([^/]+)#i', $url, $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "{$matches[0]}"
If use https change http to https, I don't know how to make it work for http and https.
I am working with PHP and WordPress right now, I need to basically run the below code to Replace text in $current_path with the text in $new_path if $current_path EXIST in $content
I would prefer to be able to iterate over an array instead of running this over and over like this, or any better method would be nice?
$content = 'www.domain.com/news-tag/newstaghere'
$current_path = 'test-tag';
$new_path = 'test/tag';
$content = str_replace($current_path, $new_path, $content);
$current_path = 'news-tag';
$new_path = 'news/tag';
$content = str_replace($current_path, $new_path, $content);
$current_path = 'ppc-tag';
$new_path = 'ppc/tag';
$content = str_replace($current_path, $new_path, $content);
str_replace() accepts array arguments:
$current_paths = array('test-tag','news-tag','ppc-tag');
$new_paths = array('test/tag','news/tag','ppc/tag');
$new_content = str_replace($current_paths, $new_paths, $content);
Or you can use a single array with strtr():
$path_map = array('test-tag'=>'test/tag', 'news-tag'=>'news/tag', 'ppc-tag'=>'ppc/tag');
$new_content = strtr($content, $path_map);
However, you seem to be doing something very generic. Maybe all you need is a regex?
$new_content = preg_replace('/(test|news|ppc)-(tag)/u', '\1/\2', $content);
Or maybe even just
$new_content = preg_replace('/(\w+)-(tag)/u', '\1/\2', $content);
$content = 'www.domain.com/news-tag/newstaghere'
$current_paths = array('test-tag','news-tag','ppc-tag');
$new_paths = array('test/tag','news/tag','ppc/tag';
$content = str_replace($current_paths, $new_paths, $content);
Array arguments can be provided for the str_replace function, as noted on the following PHP.net page:
http://php.net/manual/en/function.str-replace.php
Please see "Example #2" on the page linked above for details.
You can do that:
$content = 'www.domain.com/news-tag/newstaghere';
$content = preg_replace('~www\.domain\.com/\w++\K-(?=tag/)~', '/', $content);
I need to get the last string content of the url between / and /
For example:
http://mydomain.com/get_this/
or
http://mydomain.com/lists/get_this/
I need to get where get_this is in the url.
trim() removes the trailing slash, strrpos() finds the last occurrence of / (after it's trimmed), and substr() gets all content after the last occurrence of /.
$url = trim($url, '/');
echo substr($url, strrpos($url, '/')+1);
View output
Even better, you can just use basename(), like hakre suggested:
echo basename($url);
View output
Assuming there always is a trailing slash:
$parts = explode('/', $url);
$get_this = $parts[count($parts)-2]; // -2 since there will be an empty array element due to the trailing slash
If not:
$url = trim($url, '/'); // If there is a trailing slash in this URL instance get rid of it so we're always sure the last part is where we expect it
$parts = explode('/', $url);
$get_this = $parts[count($parts)-1];
Something like this should work.
<?php
$subject = "http://mydomain.com/lists/get_this/";
$pattern = '/\/([^\/]*)\/$/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>
Just use parse_url() and explode():
<?php
$url = "http://mydomain.com/lists/get_this/";
$path = parse_url($url, PHP_URL_PATH);
$path_array = array_filter(explode('/', $path));
$last_path = $path_array[count($path_array) - 1];
echo $last_path;
?>
You can try this:
preg_match("/http:\/\/([a-z0-9\.]+)\/(.+)\/(.*)\/?/", $url, $matches);
print_r($matches);
I am struggling to finish this regex code in PHP. I want to trim down the following url which is held in variable $text so that it goes from:
http://www.site.net/showthread.php?tid=324&pid=...
to:
showthread.php?tid=324
Thank you kindly!
Why use a regex? The parse_url method should give you all you want: http://php.net/manual/en/function.parse-url.php
Edit: working example
$someurl = 'http://www.site.net/showthread.php?tid=324&pid=...';
$urlParts = parse_url($someurl, PHP_URL_PATH | PHP_URL_QUERY);
$params = parse_str($urlParts['query']);
unset($params['pid']);
$queryString = http_build_query($params);
$newUrl = $urlParts['path'] . '?' . $queryString;
Since $urlParts['path'] start with a / and you didn't want that, you could even use
$newUrl = substr($newUrl, 1);
and be done :) Does that help at all?
This should do it:
$url = 'http://www.site.net/showthread.php?tid=324&pid=...';
$pattern = "/showthread.php\?tid=[0-9]+/";
if (preg_match($pattern, $url, $match))
print_r($match);
http://domain.name/1-As Low As 10% Downpayment, Free Golf Membership!!!
The above url will report 400 bad request,
how to convert such title to user friendly good request?
You may want to use a "slug" instead. Rather than using the verbatim title as the URL, you strtolower() and replace all non-alphanumeric characters with hyphens, then remove duplicate hyphens. If you feel like extra credit, you can strip out stopwords, too.
So "1-As Low As 10% Downpayment, Free Golf Membership!!!" becomes:
as-low-as-10-downpayment-free-gold-membership
Something like this:
function sluggify($url)
{
# Prep string with some basic normalization
$url = strtolower($url);
$url = strip_tags($url);
$url = stripslashes($url);
$url = html_entity_decode($url);
# Remove quotes (can't, etc.)
$url = str_replace('\'', '', $url);
# Replace non-alpha numeric with hyphens
$match = '/[^a-z0-9]+/';
$replace = '-';
$url = preg_replace($match, $replace, $url);
$url = trim($url, '-');
return $url;
}
You could probably shorten it with longer regexps but it's pretty straightforward as-is. The bonus is that you can use the same function to validate the query parameter before you run a query on the database to match the title, so someone can't stick silly things into your database.
See the first answer here URL Friendly Username in PHP?:
function Slug($string)
{
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-'));
}
$user = 'Alix Axel';
echo Slug($user); // alix-axel
$user = 'Álix Ãxel';
echo Slug($user); // alix-axel
$user = 'Álix----_Ãxel!?!?';
echo Slug($user); // alix-axel
You can use urlencode or rawurlencode... for example Wikipedia do that. See this link:
http://en.wikipedia.org/wiki/Ichigo_100%25
that's the php encoding for % = %25
I just create a gist with a useful slug function:
https://gist.github.com/ninjagab/11244087
You can use it to convert title to seo friendly url.
<?php
class SanitizeUrl {
public static function slug($string, $space="-") {
$string = utf8_encode($string);
if (function_exists('iconv')) {
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
}
$string = preg_replace("/[^a-zA-Z0-9 \-]/", "", $string);
$string = trim(preg_replace("/\\s+/", " ", $string));
$string = strtolower($string);
$string = str_replace(" ", $space, $string);
return $string;
}
}
$title = 'Thi is a test string with some "strange" chars ò à ù...';
echo SanitizeUrl::slug($title);
//this will output:
//thi-is-a-test-string-with-some-strange-chars-o-a-u
You could use the rawurlencode() function
To simplify just full the list of the variable $change_to and $to_change
<?php
// Just full the array list to make replacement complete
// In this space will change to _, à to just a
$to_change = [
' ', 'à', 'à', 'â','é', 'è', 'ê', 'ç', 'ù', 'ô', 'ö' // and so on
];
$change_to = [
'_', 'a', 'a', 'a', 'e', 'e', 'e','c', 'u', 'o', 'o' // and so on
];
$texts = 'This is my slug in êlàb élaboré par';
$page_id = str_replace($to_change, $change_to, $texts);