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>";
}
Related
I have little confidence when it comes to regular expressions. Writing this in PHP code.
I need to be able to filter out strings that follow this format, where the numbers can be 4~6 digits (numeric only):
$input = "This is my string with a weird ID added cause I'm a weirdo! (id:11223)";
I could simply remove the last word by finding the last position of a space via strrpos(); (it appears none of them have a trailing space from JSON feed), then use substr(); to cut it. But I think the more elegant way would be a substring. The intended output would be:
$output = trim(preg_replace('[regex]', $input));
// $output = "This is my string with a weird ID added cause I'm a weirdo!"
So this regex should match with the brackets, and the id: portion, and any contiguous numbers, such as:
(id:33585)
(id:1282)
(id:9845672)
Intending to use the preg_replace() function to remove these from a data feed. Don't ask me why they decided to include an ID in the description string... It blows my mind too why it's not a separate column in the JSON feed altogether.
Try using the pattern \(id:\d+\):
$input = "Text goes here (id:11223) and also here (id:33585) blah blah";
echo $input . "\n";
$output = preg_replace("/\(id:\d+\)/", "", $input);
echo $output;
This prints:
Text goes here (id:11223) and also here (id:33585) blah blah
Text goes here and also here blah blah
There is an edge case here, which you can see in the possible (unwanted) extract whitespace left behind after the replacement. We could try to get sophisticated and remove that too, but you should state what you expected output is.
I wrote a regex to find out href from anchor tag
My regex is
<a.*?href="(.*?)">blah<\/a> //dot is matching all
So according to me, this will start matching from <a until it finds out first href. After this it will grab the url in href until first " and then it will match for blah.
But this is matching multiple sets of anchor tags which have blah tag in end, for example:
abc
def
blah
According to me it should grab only last url as regex fits it perfectly.
To answer the question, you can swap your dot operator for a not group, to match everything but the closing tag:
<a[^>]*href="([^"]*)">def<\/a>
This (in theory) ensures that the regex pattern will only match inside a particular tag.
To not answer your question: it's often not a great idea to parse HTML with regex, unless you can be extremely sure of exactly how it's formatted. You might want to look into the PHP DOM.
I am working on a code that highlights certain words, using a regex.
Here it is:
function addRegEx($word){
return "/\b(\w+)?".$word."(\w+)?\b/i";
}
function highlight($word){
return "<span class=\"highlighted\">".$word[0]."</span>";
}
function customHighlights($searchString,$toHighlight){
$searchFor = array_map('addRegEx',$toHighlight);
$result = preg_replace_callback($searchFor,'highlight',$searchString);
return $result;
}
Lets say I use the function customHighlights to searc for the word "car" in a certain text:
Using the boundary - \b - method, the script searches for the word car in the text.
In the regex, I have added (\w+)? in front and after the word, so the script would match words that contain "car" - cars, sportcars, etc...
The problem is, it messes up the inner html, for example:
This is a great car. Click here for more
The script will match the word car in the url of the link above, adding span classes to it and messing up the html.
How would you modify the regex and avoid this?
Use a regular expression that searches for the word after the last > or beginning of text, but part between this and the word may not contain a tag start <.
See this codepad
Code
<?php
$str = 'This is a great car. Click here for more cars';
$word = 'car';
$exp = "/((^|>)[^<]*)(\b(\w+)?".$word."(\w+)?\b)/i";
$repl = "\\1<span class=\"highlighted\">\\3</span>";
var_dump(preg_replace($exp, $repl, $str));
?>
Output
string(141) "This is a great <span class="highlighted">car</span>. Click here for more <span class="highlighted">cars</span>"
Did you consider processing the text highlighting on client-side using Javascript? jQuery or similar could allow you to iterate over nodes to find where to highlight instead of working with the raw HTML.
I can't help you much with the regular expression though.
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';
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);