I have the following text:
"This is a test text. Test, comma instead of space."
I iterate through each word and want to replace each word to a distinct link. Let's say
wordToReplace
My problem is that consecutive matches of the word "test" (to use the above example) replace the href and anchor text so I'm left with links inside links which is not good at all.
(to give a base idea of my problem this is what I'm left with. It has some additional markup.)
This is a<a href="/index.php?r<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt2">text</a>/addWord" class="wordLink
info label" id="yt1">test</a>text.<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt3">Test</a><a
href="/index.php?r=texts/addWord" class="wordLink info label"
id="yt4">comma</a>instead of<a href="/index.php?r=texts/addWord"
class="wordLink info label" id="yt6">space</a>
I'm trying
preg_replace("/[^\">]".$word."[^\"<]/", $link, $text->text);
but I don't think I'm on the right track at all.
Thanks for the time
From your one line of code, I'm assuming that you have that line in a loop which iterates through all the $words you want to replace, which causes the problem.
What you need to do is put all those replacements into only one preg_replace call. For that, regexes provide alternatives. So say, your list of words consisted of test, text and this. Then you could do:
preg_replace('/(test|text|this)/', $link, $text->text);
And if you have all your words in an array $words then you can generate the regex simply with:
$wordList = implode('|', $words);
preg_replace('/('.$wordList.')/', $link, $text->text);
You might want to add an i at the very end of your regex, if your checks are supposed to be case-insenstive.
In case some of your words are parts of other words (e.g. you want to replace text and texture), you could check for word boundaries:
preg_replace('/\b('.$wordList.')\b/', $link, $text->text);
Is this what you are looking for?
EDIT: If your $link was pre-generated for every $word in your loop before, you can now replace that word with $1. If your $link was something like
$link = ''.$word.'';
you can now simply use
$link = '$1';
Related
I tried explaining this but I don't think anyone understood,
I have a lot of titles which are all different, what I'm trying to do, is get rid of every "Lyrics" word in the title, and also, everything that appears before the "-" symbol.
I managed to do the lyrics part with istr_replace
<?php echo str_ireplace('lyrics', '', get_the_title()); ?>
How can I do the second part, what can I apply to the code to make it so?
Example of what I want it to do:
"random title - more random title lyrics" turns to "more random title"
The code applied, would delete the "random title - " on every single title on my website,
I was previously given this by someone here, Idk if this would help
$string = preg_replace("/[^-]+-(.*) Lyrics/", "$1", $string);
If you're trying to do it all in one regexp, that's probably asking too much. Why not break it up into two steps: remove everything up through - (and following spaces)
$string = preg_replace('/^[^-]*-\s*/, '', $string);
and then remove the first "lyrics" (case insensitive), if any
$string = preg_replace('/lyrics/i', '', $string);
This can get more complicated -- what if there are no or multiple hyphens, what if there are no or multiple "lyrics", what do you want to do about spaces or punctuation after the hyphen and around "lyrics", can "lyrics" be part of another word, what about arbitrary capitalization of "lyrics", etc.? You need to make sure it works as expected in all these cases.
I am writing a PHP function which is supposed to convert certain keywords into links. It uses Cyrillic words in UTF-8.
So I came up with this:
function keywords($text){
$keywords = Db::get('keywords'); //array with words and corresponding links
foreach ($keywords as $value){
$keyword = $value['keyword'];
$link = $value['link'];
$text = preg_replace('/(?<!\pL)('.$keyword.')(?!\pL)/iu', '$1', $text);
}
return $text;
}
So far this runs like a charm, but now I want to replace phrases with links - phrases that may contain other keywords. For example I want the word "car" to link to one place, and "blue car" to other.
Any ideas?
As written in the comment, i post this as an answer, hoping it's been useful to you.
You could try replacing the keyword into the text firstly by using a placeholder and then, when entire text has been parsed, you can substitute those placeholders with the real words.
For example, take the phrase:
"I have a car, a blue car."
We already ordered the keywords list from longer to smaller, so we get to check "blue car"; We find it in the text, so we put the placeholder and obtain:
"I have a car, a [[1]]."
The second keyword in the list is "car"; after substitution in the text, we obtain:
"I have a [[2]], a [[1]]."
Finally, when all keywords have been substituted, you only have to replace the placeholders in their order using the preg_replace in your function, and get the text with links.
I am trying to convert specific keywords in text, which are stored in array, to the links.
Example text:
$text='This text contains many keywords, but also formated keywords.'
So now I want to convert the word keywords to the #keywords.
I used the very simple preg_replace function
preg_replace('/keywords/i',' keywords ',$text);
but obviously it converts to link also the string already formatted as a link, so I get a messy html like:
$text='This text contains many keywords, but also formated keywords" title="keywords">keywords</a>.'
Expected result:
$text='This text contains many keywords, but also formated keywords.'
Any suggestions?
THX
EDIT
We are one step from the perfect function, but still not working well in this case:
$text='This text contains many keywords, but also formated
keywords.'
In this case it replaces also the word keywords in the href, so we again get the messy code like
keywords.com/keywords" title="keywords">keywords</a>
I'm not great with regular expressions, but maybe this one will work:
/[^#>"]keywords/i
What I think it will do is ignore any instances of #keywords, >keywords, and "keywords and find the rest.
EDIT:
After testing it out, it looks like that replaces the space before the word as well, and doesn't work if keywords is the beginning of the string. It also didn't preserve original capitalization. I have tested this one, and it works perfectly for me:
$string = "Keywords and keywords, plus some more keywords with the original keywords.";
$string = preg_replace("/(?<![#>\"])keywords/i", "$0", $string);
echo $string;
The first three are replaced, preserving the original capitalization, and the last one is left untouched. This one uses a negative lookbehind and backreferences.
EDIT 2:
OP edited question. With the new example provided, the following regex will work:
$string = 'This text contains many keywords, but also formated keywords.';
$string = preg_replace("/(?<![#>\".\/])keywords/i", "$0", $string);
echo $string;
// outputs: This text contains many keywords, but also formated keywords.
This will replace all instances of keywords that are not preceded by #, >, ", ., or /.
Here is the problem:
The keyword could be inside the href, the title, or the text of the link, and anywhere in there (like if the keyword was sanity and you already had href="insanity". Or even worse, you could have a non-keyword link that happens to contain a keyword, something like:
Click here to find more keywords and such!
In the above example, even though it fits every other possible criteria (it's got spaces before and after being the easiest one to test for), it still would result in a link within a link, which I think breaks the internet.
Because of this, you need to use lookaheads and lookbehinds to check if the keyword is wrapped in a link. But there is one catch: lookbehinds have to have a defined pattern (meaning no wild cards).
I thought I'd be the hero and show you the easy fix for your issue, which would be something to the effect of:
'/(?<!\<a.?>)[list|of|keywords](?!\<\/a>)/'
Except you can't do that because the lookbehind in this case has that wildcard. Without it, you end up with a super greedy expression.
So my proposed alternative is to use regex to find all link elements, then str_replace to swap them out with a placeholder, and then replacing them with the placeholder at the end.
Here's how I did it:
$text='This text contains many keywords, but also formated keywords.';
$keywords = array('text', 'formatted', 'keywords');
//This is just to make the regex easier
$keyword_list_pattern = '['. implode($keywords,"|") .']';
// First, get all matching keywords that are inside link elements
preg_match_all('/<a.*' . $keyword_list_pattern . '.*<\/a>/', $text, $links);
$links = array_unique($links[0]); // Cleaning up array for next step.
// Second, swap out all matches with a placeholder, and build restore array:
foreach($links as $count => $link) {
$link_key = "xxx_{$count}_xxx";
$restore_links[$link_key] = $link;
$text = str_replace($link, $link_key, $text);
}
// Third, we build a nice replacement array for the keywords:
foreach($keywords as $keyword) {
$keyword_links[$keyword] = "<a href='#$keyword'>$keyword</a>";
}
// Merge the restore links to the bottom of the keyword links for one mass replacement:
$keyword_links = array_merge($keyword_links, $restore_links);
$text = str_replace(array_keys($keyword_links), $keyword_links, $text);
echo $text;
You can change your RegEx so that it only targets keywords with a space in front. Since the formatted keywords do no contain a space. Here is an example.
$text = preg_replace('/ keywords/i',' keywords',$text);
I don't consider myself a PHP "noob", but regular expressions are still new to me.
I'm doing a CURL where I receive a list of comments. Every comment has this HTML structure:
<div class="comment-text">the comment</div>
What I want is simple: I want to get, from a preg_match_all, the comments that have the word "cool" in this specific DIV tag.
What I have so far:
preg_match_all("#<div class=\"comment-text\">\bcool\b</div>#Uis", $getcommentlist, $matchescomment);
Sadly, this doesn't work. But if the REGEX is simply #\bcool\b#Uis, it will work. But I really want to capture the word "cool" in those tags.
I know I could do 2 regular expressions (one that gets all the comments, the other that filters each of them to capture the word "cool"), but I was wondering how could I do this in one preg_match_all?
I don't think I'm far from the solution, but somehow I just can't find it. Something's definitely missing.
Thank you for your time.
This should give you what you're looking for, and provide some flexibility if you want to change things a bit:
$input = '<div class="comment-text">the comment</div><div class="comment-text">cool</div><div class="comment-text">this one is cool too</div><div class="comment-text">ool</div>';
$class="comment-text";
$text="cool";
$pattern = '#<div class="'.$class.'">([^<]*'.$text.'[^<]*)</div>#s';
preg_match_all($pattern, $input, $matches);
Obviously, you need to set your input as the value for $input. After this runs, an array of the <div>s that matched will be in $matches[0] and an array of the text that matched will be in $matches[1]
You can change the class of div to match or the within-div text to require by changing the $class and $text values, respectively.
I have a situation in which I parse a body of text and replace certain phrases with links. I then need to re-parse the string to replace a second set of phrases with links. The problem arises at this point, where certain words or phrases in the second set can be substrings of phrases already replaced in the first pass.
Example: The string "blah blah grand canyon blah" will become "blah blah grand canyon blah" after the first pass. The second pass might try to replace the word "canyon" with a link, so the resulting, broken, text would read: "blah blah grand <a href="#">canyon</a> blah".
So I've been trying to use preg_replace and a regular expression to prevent nested <a> tags from occurring - by only replacing text which is not already in a link. I have tried to regexes that check based on whether there are </a> tags further on in the text but can't get these to work.
Maybe another approach is required?
Many thanks in advance!
Dave
This might work for all passes:
$string = preg_replace('/([^>]|^)grand canyon\b/','$1<a href=#>grand canyon</a>',$string);
EDIT: assuming you can afford missing when the text contains stuff like "amazonas>grand canyon"
For the second pass, you could use a regex such as:
(<a[^>]*>.*?</a>)|grand
This regex matches either a link, or the word "grand". If the link is matched, it is captured into the first (and only) capturing group. If the group matched, simply re-insert the existing link. If the word grand matches, you know it's outside a link, and you can turn it into a link.
In PHP you can do this with preg_replace_callback:
$result = preg_replace_callback('%(<a[^>]*>.*?</a>)|grand%', compute_replacement, $subject);
function compute_replacement($groups) {
// You can vary the replacement text for each match on-the-fly
// $groups[0] holds the regex match
// $groups[n] holds the match for capturing group n
if ($groups[1]) {
return $groups[1];
} else {
return "<a href='#'>$groups[0]</a>";
}