I have a doubt, it may be something simple but I have no knowledge to solve it.
I get a string in php
$ string = "[link = someUrl] Text [link]"
And I would like to turn this string into:
"<a href='someUrl'> Text <a/>"
How do I change the URL? and How Can I do the opposite?
Remember that the string belongs to a text with more strings of these gifts.
Short preg_replace solution:
$s = "[link=someUrl] Text [/link]";
$result = preg_replace('#\[[^=]+=([^]]+)\]([^[]+).*#', '<a href=\'$1\'>$2</a>', $s);
print_r($result);
The output (as web page source code):
<a href='someUrl'> Text </a>
You can use the following code
function transformText($string) {
preg_match("/\[link\=([^\]]*)\](.*?)\[\/link]/", $string, $matches);
$someUrl = $matches[1];
$text = $matches[2];
$newString = "<a href='$someUrl'>$text</a>";
return $newString;
}
$string = "[link=someUrl] Text [/link]"; // Test string
echo (transformText($string));
Live demo for the regex used : https://regex101.com/r/tzVfmH/4
Note : The above code works only if there's a single [link], [/link] pair.
If multiple occurrences are to be handled then its better to use regex search and replace, using php's preg_replace as suggested in RomanPerekhrest's answer.
Related
I want to make links using shortcuts following the pattern: controller/#/id. For example: a#3 must be rewritten to /actions/view/3, and t#28 must be a link to /tasks/view/28. I think preg_replace is an "easy" way to achieve this, but I'm not that good with regular expressions and I don't know how to "reuse" the digits from the search-string within the result. I think I need something like this:
$search = array('/a#\d/', '/t#\d/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);
Can someone point me in the right direction?
You can "reuse" the numbers from the search strings using capturing groups, denoted by brackets ().
Try this -
$text = "a#2 a#3 a#5 a#2 t#34 t#34 t#33 t#36";
$search = array('/\ba#(\d+)\b/', '/\bt#(\d+)\b/');
$replace = array('/actions/view/$1', '/tasks/view/$1');
$text = preg_replace($search, $replace, $text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/
The above answer works, but if you need to add more of those search values, you can store those keys in separate array and you can use preg_replace_callback.This also does the same thing, but now, you only need to add more (alphabets)keys in the array and it will replace it accordingly. Try something like this-
$arr = Array(
"a"=> "/actions/view/",
"t"=> "/tasks/view/"
);
$text = preg_replace_callback("/\b([a-z]+)#(\d+)\b/", function($matches) use($arr){
var_dump($matches);
return $arr[$matches[1]].$matches[2];
},$text);
var_dump($text);
/**
OUTPUT-
string '/actions/view/2 /actions/view/3 /actions/view/5 /actions/view/2 /tasks/view/34 /tasks/view/34 /tasks/view/33 /tasks/view/36' (length=123)
**/
Since the number is not replaced you can use strtr (if it is not too ambigous) :
$trans = array('a#' => '/actions/view/', 't#' => '/tasks/view/');
$text = strtr($text, $trans);
if you can use this, it will be faster than processing a string two times with a regex.
I'm working on a bb-code replacement function when a user wants to post a smiley.
The problem is, that if someone uses a bb-code smiley that doesn't exists, it results in an empty post because the browser will not display the (non-existing) emoticon.
Here's my code so far:
// DO [:smiley:]
$convert_smiley = preg_match_all('/\[:(.*?):\]/i', $string, $matches);
if( $convert_smiley )
{
$string = preg_replace('/\[:(.*?):\]/i', "<i class='icon-smiley-$1'></i>", $string, $convert_smiley);
}
return $string;
The bb-code for a smiley usually looks like [:smile:] or like [:sad:] or like [:happy:] and so on.
The code above is working well, until someone post a bb-code that doesn't exists, so what I am asking for is a fix for non existing smileys.
Is there a possibility, in example to create an array, like array('smile', 'sad', 'happy') and only bb-code that matches one or more in this array will be converted?
So, after the fix, posting [:test:] or just [::] should not be converted and should be posted as original text while [:happy:] will be converted.
Any ideas? Thanks!
I put your possible smiley’s in non-grouping parentheses with or symbol in a regexp:
<?php
$string = 'looks like [:smile:] or like [:sad:] or like [:happy:] [:bad-smiley:]';
$string = preg_replace('/\[:((?:smile)|(?:sad)|(?:happy)):\]/i', "<i class='icon-smiley-$1'></i>", $string);
print $string;
Output:
looks like <i class='icon-smiley-smile'></i> or like <i class='icon-smiley-sad'></i> or like <i class='icon-smiley-happy'></i> [:bad-smiley:]
[:bad-smiley:] is ignored.
A simple workaround:
$string ="[:clap:]";
$convert_smiley = preg_match_all('/\[:(.*?):\]/i', $string, $matches);
$emoticons = array("smile","clap","sad"); //array of supported smileys
if(in_array($matches[1][0],$emoticons)){
//smily exists
$string = preg_replace('/\[:(.*?):\]/i', "<i class='icon-smiley-$1'></i>", $string, $convert_smiley);
}
else{
//smily doesn't exist
}
Well, the first issue is you are setting $convert_smiley to the true/false value of the preg_match_all() instead of parsing the results. Here is how I reworked your code:
// Test strings.
$string = ' [:happy:] [:frown:] [:smile:] [:foobar:]';
// Set a list of valid smileys.
$valid_smileys = array('smile', 'sad', 'happy');
// Do a `preg_match_all` against the smiley’s
preg_match_all('/\[:(.*?):\]/i', $string, $matches);
// Check if there are matches.
if (count($matches) > 0) {
// Loop through the results
foreach ($matches[1] as $smiley_value) {
// Validate them against the valid smiley list.
$pattern = $replacement = '';
if (in_array($smiley_value, $valid_smileys)) {
$pattern = sprintf('/\[:%s:\]/i', $smiley_value);
$replacement = sprintf("<i class='icon-smiley-%s'></i>", $smiley_value);
$string = preg_replace($pattern, $replacement, $string);
}
}
}
echo 'Test Output:';
echo htmlentities($string);
Just note that I chose to use sprintf() for the formatting of content & set $pattern and $replacement as variables. I also chose to use htmlentities() so the HTML DOM elements can easily be read for debugging.
I have to extract the email from the following string:
$string = 'other_text_here to=<my.email#domain.fr> other_text_here <my.email#domain.fr> other_text_here';
The server send me logs and there i have this kind of format, how can i get the email into a variable without "to=<" and ">"?
Update: I've updated the question, seems like that email can be found many times in the string and the regular expresion won't work well with it.
You can try with a more restrictive Regex.
$string = 'other_text_here to=<my.email#domain.fr> other_text_here';
preg_match('/to=<([A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4})>/i', $string, $matches);
echo $matches[1];
Simple regular expression should be able to do it:
$string = 'other_text_here to=<my.email#domain.fr> other_text_here';
preg_match( "/\<(.*)\>/", $string, $r );
$email = $r[1];
When you echo $email, you get "my.email#domain.fr"
Try this:
<?php
$str = "The day is <tag> beautiful </tag> isn't it? ";
preg_match("'<tag>(.*?)</tag>'si", $str, $match);
$output = array_pop($match);
echo $output;
?>
output:
beautiful
Regular expression would be easy if you are certain the < and > aren't used anywhere else in the string:
if (preg_match_all('/<(.*?)>/', $string, $emails)) {
array_shift($emails); // Take the first match (the whole string) off the array
}
// $emails is now an array of emails if any exist in the string
The parentheses tell it to capture for the $matches array. The .* picks up any characters and the ? tells it to not be greedy, so the > isn't picked up with it.
What I'm trying to do is, if it exists, remove an occurrence of text inside a 'shortcode', eg: Here's some content [shortcode]I want this text removed[/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content.
It seems like a pretty simple thing to do but I can't figure it out.. =/
The shortcode will only show up once in the entire string.
Thanks in advance for help.
Try this:
$var = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content";
$startTag = "[shortcode]";
$endTag = "[/shortcode]";
$pos1 = strpos($var, $startTag) + strlen($startTag);
$pos2 = strpos($var, $endTag);
$result = substr_replace($var, '', $pos1, $pos2-$pos1);
It's very easy to do with preg_replace(). For your purpose, use /\[shortcode\].*\[\/shortcode\]/ as pattern.
$replace = "[shortcode][/shortcode]";
$filteredText = preg_replace("/\[shortcode\].*\[\/shortcode\]/", $replace, $yourContent);
See http://php.net/manual/en/function.preg-replace.php for more details.
One can use strpos() to find the position of [substring] and [/substring] in your string and replace the text with a whitespace via substr_replace()
if you do not want to bother with regular expessions:
if you do have the [shortcode] tag inside the string, than it is really no problem: just use a nested use of substr:
substr($string,0,strpos($string,'[substring]')+11)+substr($string,strpos($string,'[/substring]'),strlen($string))
where the first substr cuts the string to the start of the string to cut and the second adds the remaining stuff of the string.
see here:
http://www.php.net/manual/en/function.substr.php
http://www.php.net/manual/en/function.strpos.php
use regex in php to get rid of it.
preg_replace (shortcode, urText, '', 1)
$string = "[shortcode]I want this text removed[/shortcode]";
$regex = "#\[shortcode\].*\[\/shortcode\]#i";
$replace = "[shortcode][/shortcode]";
$newString = preg_replace ($regex, $replace, $string, -1 );
$content = "Here's some content [shortcode]I want this text removed[/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content";
print preg_replace('#(\[shortcode\])(.*?)(\[/shortcode\])#', "$1$3", $content);
Yields:
Here's some content [shortcode][/shortcode] Some more content to be changed to Here's some content [shortcode][/shortcode] Some more content
I need to strip a URL using PHP to add a class to a link if it matches.
The URL would look like this:
http://domain.com/tag/tagname/
How can I strip the URL so I'm only left with "tagname"?
So basically it takes out the final "/" and the start "http://domain.com/tag/"
For your URL
http://domain.com/tag/tagname/
The PHP function to get "tagname" is called basename():
echo basename('http://domain.com/tag/tagname/'); # tagname
combine some substring and some position finding after you take the last character off the string. use substr and pass in the index of the last '/' in your URL, assuming you remove the trailing '/' first.
As an alternative to the substring based answers, you could also use a regular expression, using preg_split to split the string:
<?php
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);
?>
(The reason for the -2 is because due to the ending /, the final element of the array will be a blank entry.)
And as an alternate to that, you could also use preg_match_all:
<?php
$ptn = "/[a-z]+/";
$str = "http://domain.com/tag/tagname/";
preg_match_all($ptn, $str, $matches);
$tagname = $matches[count($matches)-1];
echo($tagname);
?>
Many thanks to all, this code works for me:
$ptn = "/\//";
$str = "http://domain.com/tag/tagname/";
$result = preg_split($ptn, $str);
$tagname = $result[count($result)-2];
echo($tagname);