Replace names in text with links - php

I want to replace names in a text with a link to there profile.
$text = "text with names in it (John) and Jacob.";
$namesArray("John", "John Plummer", "Jacob", etc...);
$LinksArray("<a href='/john_plom'>%s</a>", "<a href='/john_plom'>%s</a>", "<a href='/jacob_d'>%s</a>", etc..);
//%s shout stay the the same as the input of the $text.
But if necessary a can change de array.
I now use 2 arrays in use str_replace. like this $text = str_replace($namesArray, $linksArray, $text);
but the replace shout work for name with a "dot" or ")" or any thing like that on the end or beginning. How can i get the replace to work on text like this.
The output shout be "text with names in it (<a.....>John</a>) and <a ....>Jacob</a>."

Here is an example for a single name, you would need to repeat this for every element in your array:
$name = "Jacob";
$url = "<a href='/jacob/'>$1</a>";
$text = preg_replace("/\b(".preg_quote($name, "/").")\b/", $url, $text);

Try something like
$name = 'John';
$new_string = preg_replace('/[^ \t]?'.$name.'[^ \t]/', $link, $old_string);
PHP's preg_replace accepts mixed pattern and subject, in other words, you can provide an array of patterns like this and an array of replacements.

Done, and no regex:
$text = "text with names in it (John) and Jacob.";
$name_link = array("John" => "<a href='/john_plom'>",
"Jacob" => "<a href='/jacob'>");
foreach ($name_link as $name => $link) {
$tmp = explode($name, $text);
if (count($tmp) > 1) {
$newtext = array($tmp[0], $link, $name, "</a>",$tmp[1]);
$text = implode($newtext);
}
}
echo $text;
The links will never change for each given input, so I'm not sure whether I understood your question. But I have tested this and it works for the given string. To extend it just add more entries to the $name_link array.

Look for regular expressions. Something like preg_replace().
preg_replace('/\((' . implode('|', $names) . ')\)/', 'link_to_$1', $text);
Note that this solution takes the array of names, not just one name.

Related

Replace all the matches in a string that matches array values

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>";

PHP: regex to replace a#3 in string

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.

Preg Replace with mentions

I have some problems with the preg_replace.
I would change the mentions in a links but the name isn't a username.
So in the name there are spaces, i found a good solution but i don't know to do it.
Sostantially i would that preg_replace the words that are between # and ,
For example:
#John Doeh, #Jenna Diamond, #Sir Duck Norman
and replace to
VAL
How do I do it?
I think that you want it like:
John Doeh
For this try:
$myString="#John Doeh, #Jenna Diamond, #Sir Duck Norman";
foreach(explode(',',$myString) as $str)
{
if (preg_match("/\\s/", $str)) {
$val=str_replace("#","",trim($str));
echo "<a href='user.php?name=".$val."'>".$val."</a>";
// there are spaces
}
}
Based on my assumption you want to remove strings which start with #Some Name, in a text like: #Some Name, this is a message.
Then replace that to an href, like: First_Name
If that is the case then the following regex will do:
$str = '#First_Name, say something';
echo preg_replace ( '/#([[:alnum:]\-_ ]+),.*/', '$1', $str );
Will output:
First_Name
I also added support for numbers, underscores and dashes. Are those valid in a name aswell? Any other characters that are valid in a #User Name? Those are things that are important to know.
Two methods:
<?php
// preg_replace method
$string = '#John Doeh, #Jenna Diamond, #Sir Duck Norman';
$result = preg_replace('/#([\w\s]+),?/', '$1', $string);
echo $result . "<br>\n";
// explode method
$arr = explode(',', $string);
$result2 = '';
foreach($arr as $name){
$name = trim($name, '# ');
$result2 .= ''.$name.' ';
}
echo $result2;
?>

How to create an hyperlink in a paragraph using php

I would like to create hyperlinks to the words in a paragraph.
For instance if the "Jim Carrey" name is in the array matches the word in string, then the Jim Carrey name should be in Hyperlink of "www.domian.net/name(Jim Carrey)" .
If the "mask" word in the array matches the word in string then it should be replace with corresponding url like "www.domian.net/mask"
<?php
$string="Jim Carrey found the new Mask";
$array=array("Jim Carrey","mask");
echo preg_replace( '/\b('.implode( '|', $array ).')\b/i', '$1', $string );
?>
You seem to have the right idea about how to put a link around the chosen text, but you seem to have not even tried to put in an href. Which is a shame, since it's as simple as typing in the URL with whatever parameter you want.
However, it does get a little complicated because you don't want the same thing both times (you want the literal word in one, but you want name(WORD) in the other). You could try this:
$array = array("Jim Carrey"=>"name(Jim Carrey)","mask"=>"mask");
echo preg_replace_callback("/\b".implode("|",array_keys($array))."\b/i",
function($m) use ($array) {
return "".$m."";
},$string);
<?php
$string="Jim Carrey found the new Mask";
$arr=array("Jim Carrey","Mask");
foreach($arr as $val)
$string = str_replace($val, '' . $val . '', $string);
echo $string;
?>

Slice sentences in a text and storing them in variables

I have some text inside $content var, like this:
$content = $page_data->post_content;
I need to slice the content somehow and extract the sentences, inserting each one inside it's own var.
Something like this:
$sentence1 = 'first sentence of the text';
$sentence2 = 'second sentence of the text';
and so on...
How can I do this?
PS
I am thinking of something like this, but I need somekind of loop for each sentence:
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);
$sentence1 = $match[1];
$sentence2 = $match[2];
Ty:)
Do you need them in variables? Can't you use a array?
$sentence = explode(". ", $page_data->post_content);
EDIT:
If you need variables:
$allSentence = explode(". ", $page_data->post_content);
foreach($allSentence as $key => $val)
{
${"sentence". $key} = $val;
}
Assuming each sentence ends with full stop, you can use explode:
$content = $page_data->post_content;
$sentences = explode('.', $content);
Now your sentences can be accessed like:
echo $sentences[0]; // 1st sentence
echo $sentences[1]; // 2nd sentence
echo $sentences[2]; // 3rd sentence
// and so on
Note that you can count total sentences using count or sizeof:
echo count($sentences);
It is not a good idea to create a new variable for each sentence, imagine you might have long piece of text which would require to create that number of variables there by increasing memory usage. You can simply use array index $sentences[0], $sentences[1] and so on.
Assuming a sentence is delimited by terminating punctuation, optionally followed by a space, you can do the following to get the sentences in an array.
$sentences = preg_split('/[!?\.]\s?/', $content);
You may want to trim any additional spaces as well with
$sentences = array_map('trim', $sentences);
This way, $sentences[0] is the first, $sentences[1] is the second and so on. If you need to loop through them you can use foreach:
foreach($sentences as $sentence) {
// Do something with $sentence...
}
Don't use individually named variables like $sentence1, $sentence2 etc. Use an array.
$sentences = explode('.', $page_data->post_content);
This gives you an array of the "sentences" in the variable $page_data->post_content, where "sentences" really means sequences of characters between full stops. This logic will get tripped up wherever a full stop is used to mean something other than the end of a sentence (e.g. "Mr. Watson").
Edit: Of course, you can use more sophisticated logic to detect sentence boundaries, as you have suggested. You should still use an array, not create an unknown number of variables with numbers on the ends of their names.

Categories