This is the code I currently have. How would I tweak it to include http:// in the href in the returned result every time? Currently, http:// is not in the returned result unless it's in the original string variable $text. I wish to have it added to the href if it is not in the original $text. Thanks!
function urlfixer($text){
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
Since you don't know if your $url has http:// on it or not just stick it on the beginning, and then make sure it's stripped just in case.
$url = 'http://' . str_replace('http://','',$url);
return sprintf('<a rel="nofollow" href="%s">%s</a>', $url, $text);
$url = array_shift($matches);
if( substr($url,0,6)!='http://' ) {
$url='http://'.$url;
}
something like this should do it
Related
I have URLs like this:
http://www.mywebsite.com/carmake/ABCDEFG/123456789
http://www.mywebsite.com/carmake/AAABBBC/124532532
http://www.mywebsite.com/carmake/BNDFKNV/463634213
and I want to change them to this:
http://www.mywebsite.com/carmake/parts/123456789
http://www.mywebsite.com/carmake/parts/124532532
http://www.mywebsite.com/carmake/parts/463634213
How can I change the text between the last to slashes to parts in functions.php
https://regex101.com/r/sH1wA1/1
<?php
$string = 'http://www.mywebsite.com/carmake/ABCDEFG/123456789';
$pattern = '/(.*\/).*\/([^\/]*$)/';
$replacement = '${1}parts/${2}';
echo preg_replace($pattern, $replacement, $string);
?>
Try this:
<?php
$url = "http://www.mywebsite.com/carmake/ABCDEFG/123456789";
$parts = parse_url($url);
$path = $parts['path'];
$pos = strpos($path, '/', 9);
$sub = substr($path, 9, $pos - 9);
$url = str_replace($sub, 'parts', $url);
Split to segments, change and collect back
$a = 'http://www.mywebsite.com/carmake/BNDFKNV/463634213';
$to = 'parts';
$s = explode('/', $a);
$s[count($s)-2] = $to;
echo implode('/', $s);
I am trying to replace this "iwdnowfreedom[body_style][var]" with this "iwdnowfreedom_body_style_var" in the name attributes of a variable. There could be several array keys but for my situation stripping them out shouldn't result in any issues.
Here is the code I have so far:
$pattern = '/name\\s*=\\s*["\'](.*?)["\']/i';
$replacement = 'name="$2"';
$fixedOutput = preg_replace($pattern, $replacement, $input);
return $fixedOutput;
How can I fix this to work properly?
You could try using the build in str_replace function to achieve what you are looking for (assuming there are no nested bracked like "test[test[key]]"):
$str = "iwdnowfreedom[body_style][var]";
echo trim( str_replace(array("][", "[", "]"), "_", $str), "_" );
or if you prefer regex (nested brackets work fine with this method):
$input = "iwdnowfreedom[body_style][var]";
$pattern = '/(\[+\]+|\]+\[+|\[+|\]+)/i';
$replacement = '_';
$fixedOutput = trim( preg_replace($pattern, $replacement, $input), "_" );
echo $fixedOutput;
I think you also meant that you might have a string such as
<input id="blah" name="test[hello]" />
and to parse the name attribute you could just do:
function parseNameAttribute($str)
{
$pos = strpos($str, 'name="');
if ($pos !== false)
{
$pos += 6; // move 6 characters forward to remove the 'name="' part
$endPos = strpos($str, '"', $pos); // find the next quote after the name="
if ($endPos !== false)
{
$name = substr($str, $pos, $endPos - $pos); // cut between name=" and the following "
return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $name), '_');
}
}
return "";
}
OR
function parseNameAttribute($str)
{
if (preg_match('/name="(.+?)"/', $str, $matches))
{
return trim(preg_replace('/(\[+\]+|\]+\[+|\[+|\]+)/i', '_', $matches[1]), '_');
}
return "";
}
I found this code posted on SO to change text links into hyperlinks:
function auto_link_text($text)
{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
However, it seems to change them into hyperlinks even if they are already a part of a hyperlink so you end up with something like <a href="<a href (etc). I figure what I could do is check for an already formatted hyperlink and if I don't find one, I can do that function. Or even put the check in the function. So something like:
function auto_link_text($text)
{
if preg_match(proper stuff in here){
return $text;
}else{
$pattern = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
$callback = create_function('$matches', '
$url = array_shift($matches);
$url_parts = parse_url($url);
$text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
$text = preg_replace("/^www./", "", $text);
$last = -(strlen(strrchr($text, "/"))) + 1;
if ($last < 0) {
$text = substr($text, 0, $last) . "…";
}
return sprintf(\'<a rel="nowfollow" href="%s">%s</a>\', $url, $text);
');
return preg_replace_callback($pattern, $callback, $text);
}
}
Or perhapse the regex in the function should be changed.
Add (?<!href=") just after the first # of your regex. This will ensure that it's not already inside a tag.
I have a string in php formatted like this:
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
http://bbbbbbbbbbbbbbb
In this case I wouldn't recommend regex but a simple substring or explode
$data = "http://aaaaaaaaaa/*http://bbbbbbbbbbb"
$parts = explode('*', $data);
echo $parts[1];
fin :)
You don't need regular expressions at all in this case:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
echo substr($str, strpos($str, 'http://', 1));
Hi This would help you to get the address:
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
Here is the regular expression way:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
$url = preg_replace("/^.*(http:\/\/.*[^(http:\/\/)+])$/", "$1", $str);
echo $url;
Here is a clean solution: grab everything after the last occurrence of "http://".
$start = strrpos($input, 'http://');
$output = substr($input, $start);
I want to filter the input text if it's got A URL inside it.
By URL I mean that every thing that corresponds to a valid internet address like www.example.com, example.com, http://www.example.com, http://example.com/foo/bar.
I think I've gotta use regular expressions and the preg_match function so I need the correct regexp pattern for this purpose.
I'd be very grateful if anybody could give me that.
This article has a nice regex for matching urls: http://daringfireball.net/2010/07/improved_regex_for_matching_urls
For PHP you would need to escape the regex properly, for example like this:
$text = "here is some text that contains a link to www.example.com, and it will be matched.";
preg_match("/(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/", $text, $matches);
var_dump($matches);
$html = "http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
You can surf the internet anonymously at https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi.";
preg_match_all('/\b((?P<protocol>https?|ftp):\/\/(?P<domain>[-A-Z0-9.]+)(?P<file>\/[-A-Z0-9+&##\/%=~_|!:,.;]*)?(?P<parameters>\?[A-Z0-9+&##\/%=~_|!:,.;]*)?)/i', $html, $urls, PREG_PATTERN_ORDER);
$urls = $urls[1][0];
Will match:
http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
You can surf the internet anonymously at https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi.
To loop results you can use:
for ($i = 0; $i < count($urls[0]); $i++) {
echo $urls[1][$i]."\n";
}
will output:
http://www.scroogle.org
http://www.scroogle.org/
http://www.scroogle.org/index.html
http://www.scroogle.org/index.html?source=library
https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi
cheers, Lob
Found here: http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/
Functions from WordPress.
function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];
if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "$url" . $ret;
}
function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "$dest" . $ret;
}
function _make_email_clickable_cb($matches) {
$email = $matches[2] . '#' . $matches[3];
return $matches[1] . "$email";
}
function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?#\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?#\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)#(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}
Usage:
$string = 'I have some texts here and also links such as http://www.youtube.com , www.haha.com and lol#example.com. They are ready to be replaced.';
echo make_clickable($string);