I want to replace all image contained in a string, which is like:
<img src="data:image/png;base64,IMAGE DATA
with a reference to a cid.
Since the images can't get the same cid's, i need to replace them with an increment. But i don't know how to. Only thing i've found so far is following code, which replaces the string with the same:
$string = 'normal text [everythingheregone] after text ';
$pattern = '\[.*?]';
$replacement = '[test]'
echo preg_replace($pattern, $replacement, $string);
//normal text [test] after text
Do you have any ideas?
Shame on me, i should've searched a little bit more:
Here is what i've found out on replacing with increment:
$count = 0;
preg_replace_callback('/test/', 'rep_count', $content);
function rep_count($matches) {
global $count;
return 'test' . $count++;
}
Related
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.
I have a string that I am checking for matches using my array and if there are any matches I want to replace those matches with the same words, but just styled red and then return all the string with the colored words included in one piece. This is what I have tried:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
echo '<p>' . str_replace($misspelledOnes,"<span style='color:red'>". $misspelledOnes . "</span>". '</p>', $string;
But of course this doesn't work, because the second parameter of str_replace() can't be an array. How to overcome this?
The most basic approach would be a foreach loop over the check words:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
foreach ($misspelledOnes as $check) {
$string = str_replace($check, "<span style='color:red'>$check</span>", $string);
}
echo "<p>$string</p>";
Note that this does a simple substring search. For example, if you spelled "with" properly, it would still get caught by this. Once you get a bit more familiar with PHP, you could look at something using regular expressions which can get around this problem:
$string = 'This is a brovn fox wit legs.';
$misspelledOnes = array('wit', 'brovn');
$check = implode("|", $misspelledOnes);
$string = preg_replace("/\b($check)\b/", "<span style='color:red'>$1</span>", $string);
echo "<p>$string</p>";
I have a hashtag system: (Note: $body is a variable that is a post that a user submits. The hashtags are in the posts.) I have tried to do this using regex but have found this method to be as equally efficient and a bit easier to follow.
<?php
$string = $body;
$htag = "#";
$arr = explode(" ", $string);
$arrc = count($arr);
$i = 0;
while($i < $arrc) {
if(substr($arr[$i], 0, 1) === $htag) {
$arr[$i] = "<a href = 'category.php?#=$arr[$i]'>".$arr[$i]."</a>";
}
$i++;
}
$string = implode(" ", $arr);
?>
Then, $string is echoed later in the page.
My problem with this is that my method for linking the hashtag to the category page using the php array element. On this page I want to call the word that was "hashtaged" and use a mysql query to get posts that have the hashtags. However, when I call the $arr[$i], to be echoed, I get an error:
Undefined offset: 1 on the line in which I call this array element
into another variable.
Is there any way I can complete this task in a better and more effective way?
Okay, so this can be greatly simplified using some regex and PHP's preg_replace function. #Doge was on the right track, but in my tests, \b didn't quite give the results that I think you want.
Basically, you can replace almost all of what you have with
$newText = preg_replace("/#(\w+)/", "<a href='category.php?tag=$1'>#$1</a>", $text);
As in…
$text = "This is a #hashtag within some #awesometext.";
$newText = preg_replace("/#(\w+)/", "<a href='category.php?tag=$1'>#$1</a>", $text);
echo $newText;
The result of this would be…
This is a <a href='category.php?tag=hashtag'>#hashtag</a> within some <a href='category.php?tag=awesometext'>#awesometext</a>.
See it in action here
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.
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