Preg Replace with mentions - php

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

Related

Separate string in php by upper case letters

I'm developing an application that takes a full name of a person and then processes it. For example, if the user enters the name like this:
"AlanMichel"
Then the result must be:
"Alan Michel"
I didn't know how I can do that in the php. Anyone can help please?
You can do:
$str = "AlanMichel";
$name = preg_split('/(?=[A-Z])/',$str);
echo implode( " ", $name );
This will result to:
Alan Michel
Try this
function splitAtUpperCase($s) {
return preg_split('/(?=[A-Z])/', $s, -1, PREG_SPLIT_NO_EMPTY);
}
$str = "AlanMichel";
$strArray = splitAtUpperCase($str));
echo $strArray[0]; //first name
echo $strArray[1]; //second name
Output
Alan
Michel
If you don't need the array itself, you can just preprend uppercase characters (except the first) with a space
echo preg_replace('/(?<!^)([A-Z])/', ' \\1', $str);

How to Rename Uppercase Each Words with dash, underscore, brackets and capital words?

I want to rename the following statement:
<?php
$sentence = "I-am-a-GOOD-programmer-(but-only-in-PHP)";
$do = ucwords($sentence);
echo $do;
?>
the above code will give output as:
I-am-a-GOOD-programmer-(but-only-in-php)
How do I get the output as:
I-Am-A-Good-Programmer-(But-Only-In-Php)
$sentence = "I-am-a-good-programmer-(but-only-in-PHP)";
$sentence = preg_replace_callback('/(^|[-(])(\w+)/', function ($match) { return $match[1] . ucwords($match[2]); }, $sentence );
var_dump($sentence);
will result in:
string(40) "I-Am-A-Good-Programmer-(But-Only-In-PHP)"
^|[-(] means the beginning or either a - or ( and can be easily expanded with any other chars you need, alternatively you could your \W, which means any non-word character.
\w+ means word-character (alphabetical characters).
<?php
$msg = 'I-am-a-good-programmer-(but-only-in-PHP)';
$msg_replaced = preg_replace_callback('#([^\w]*)?(\w+)([^\w]*)?#', function($matched)
{
return $matched[1] . ucwords($matched[2]) . $matched[3];
}, $msg);
echo $msg_replaced;//I-Am-A-Good-Programmer-(But-Only-In-PHP)
?>
Found a solution to the problem:
<?php
$sentence = "I-am-a-GOOD-programmer-(but-only-in-PHP)";
$sentence = str_replace("-"," ",$sentence);
$do = ucfirst($sentence);
echo $do;
?>
Its gives output as I desired:
I Am A Good Programmer (But Only In Php)

PHP preg_replace url get parameters in string

Thanks to #s.d.a.p.e I've come a step close but I'm not quite there yet.
What I'm trying to do is replace all instances of a string in a block of text. I want to replace something like this:
user is ?user_id=34&first_name=Ralph so is ?user_id=1 also
With this:
user is /user/34/ so is /user/1/ also
Here is the preg_replace code I'm using:
$pattern = '#\?user_id=([0-9]+)#';
$replace = '/user/$1/';
echo preg_replace($pattern,$replace,$string);
With that pattern I end up with this:
user is /user/34/&first_name=Ralph so is /user/1/ also
Thanks again.
try this:
$string = "user is ?user_id=34&first_name=Ralph so is ?user_id=1 also";
$result = preg_replace('/\?(user)_id=(\d+)(.*?)(?! )/i', '/$1/$2/$3', $string );
echo $result ;
Output:
user is /user/34/&first_name=Ralph so is /user/1/ also
DEMO
I'd use this:
$string = 'user is ?user_id=34&first_name=Ralph so is ?user_id=1 also';
$pattern = '#\?user_id=([0-9]+)\S*#';
$replace = '/user/$1/';
echo preg_replace($pattern, $replace, $string);
Where \S stands for any character that is not a space.
Output:
user is /user/34/ so is /user/1/ also
print preg_replace(
'#\?user_id=([0-9]+)\&(first_name=(?:.*))#',
'/user/$1?$2',
'?user_id=34&first_name=Ralph'
);
result :
/user/34?first_name=Ralph if get it right..

php preg_match_all preg_replace array issue

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.

Replace names in text with links

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.

Categories