i need the following -
if i have a sentence
$str = "i like programming very much";
and i search for a word
$word = "r";
i expect it to return the sentence
"i like *p***r***og***r***aming* *ve***r***y* much"
I wrote the following regex for it, but it sometimes doesn't work.
$str = preg_replace("/([^\s{".preg_quote($word)."}]*?)(".preg_quote($word).")([^\s{".preg_quote($word)."}]*)/siu","<span class='pice1'>$1</span><span class='pice2'>$2</span><span class='pice1'>$3</span>",$str);
Could you tell me what i wrote wrong?
Thanks
UPDATE:
for example it doesn't work when
$str = "ameriabank"; and $word = "ab";
...
Why dont't you just use str_replace()? I think it's more simple
$search = "ab";
$word = "ameriabank";
$newstr = "<span class=\"pice1\">".str_replace($search, $word, "</span><span class=\"pice3\">".$search."</span></span class=\"pice1>\")."</span>";
$str = "i like programming very much";
$w = "r";
echo preg_replace("/($w)/", "<b>$1</b>", $str);
Output:
i like p<b>r</b>og<b>r</b>amming ve<b>r</b>y much
Answer to the comment: do it in two steps.
$str = "i like programming very much ready tear";
$w = "r";
$str = preg_replace("/\\b((?:\\w+|\\b)$w(\\w+|\\b))\\b/", "<i>$1</i>", $str);
$str = preg_replace("/($w)/", "<b>$1</b>", $str);
echo $str;
output:
i like <i>p<b>r</b>og<b>r</b>amming</i> <i>ve<b>r</b>y</i> much <i><b>r</b>eady</i> <i>tea<b>r</b></i>
visit highlight multiple keywords in search and be amazed.
What about this way :
$str = "i like programming very much";
$word = "r";
$list = explode(' ',$str);
for($i=0; $i<count($list); $i++) {
if(preg_match("/$word/", $list[$i])) {
$list[$i] = '<i>'.preg_replace("/$word/siu", "<b>$word</b>", $list[$i]).'</i>';
}
}
$str = implode(' ',$list);
echo $str,"\n";
$str = "i like programming very much";
$word = "r";
function highlight($matches)
{
global $word;
return '<span class="pice1">'.str_replace($word,'<span class="pice2">'.$word.'</span>',$matches[0]).'</span>';
}
echo $str = preg_replace_callback("/([^\s]*?".preg_quote($word, '/')."[^\s]*)/siu", highlight, $str);
do the job(and it works with foreign languages too)...
Related
This is my string for example:
$x = " i love you/i love her/you love me/you love me "
and i wanted in every blank space to put - so i use:
$y = preg_replace(" ","-",$x);
and i get:
$y = " i-love-you/i-love-her/you-love-me/you-love-me "
in this string i have double expresion YOU LOVE ME, in that case when i have that, i want to add in other not one -, i want to add 2 --
so my final string will look like:
$y = " i-love-you/i-love-her/you-love-me/you--love--me "
Can you help me with these, cause if i use preg replace it will have influence on whole string?
Try This simple code
$x = "i love you/i love her/you love me/you love me";
$strArr = explode("/",$x);
$temp = array();
foreach($strArr as $value){
if(in_array($value,$temp)){
$result[]=str_replace(" ","--",$value);
}else{
$result[]=str_replace(" ","-",$value);
}
$temp[] = $value;
}
echo implode("/",$result);
You can to do it by both ways like regex or non-regex way but this what I got in my mind with array_count_values() and str_replace(). Hope it'll help you :)
<?php
$x = " i love you/i love her/you love me/you love me ";
$sentence = explode('/',trim($x));
$value_counts = array_count_values($sentence);
$expected_result = [];
foreach($value_counts as $k=>$v){
if($v<2){
$expected_result[] = str_replace(' ','-',$k);
}else{
$expected_result[] = str_replace(' ','-',$k);
for($i=2;$i<=$v;$i++){
$expected_result[] = str_replace(' ','--',$k);
}
}
}
echo " ".implode('/', $expected_result)." ";
Output:
i-love-you/i-love-her/you-love-me/you--love--me
DEMO: https://3v4l.org/Hh6Pj
Another more verbose and likely slower method :{
function format_string($x)
{
//trim whitespace to avoid "-" at beginning and end
$x = str_replace(" ","-",trim($x));
// create an array of each entry
$entries = explode("/", $x);
//count each entry
$entry_counts = array_count_values($entries);
foreach($entry_counts as $string => $count){
if($count == 2){
$needs_updating = $string;
}
}
if(isset($needs_updating)){
foreach($entries as $index => &$entry){
if($entry == $needs_updating){
$entries[$index] = str_replace("-", "--",$entry);
}
}
return implode("/", $entries);
}
return implode("/", $entries);
}
Starting with the original string, you can match the slash separated phrases and do the space replacement in a callback function that keeps track of phrases as it goes. If one of the phrases has already appeared, replace the spaces with double dashes instead of single.
$pattern = '/(?<=^|\/).+?(?=\/|$)/';
$phrases = [];
$y = preg_replace_callback($pattern, function($phrase) use (&$phrases) {
$separator = in_array($phrase[0], $phrases) ? '--' : '-';
$phrases[] = $phrase[0];
return str_replace(' ', $separator, $phrase[0]);
}, trim($x));
Here is my go:
$x = " i love you/i love her/you love me/you love me ";
$x = preg_replace_callback('/([^\/]+)\/(\1)?/', function($match){
if(isset($match[2])){
return str_replace(' ', '-', trim($match[1])).'/'.str_replace(' ', '--', trim($match[2]));
}else{
return str_replace(' ', '-', trim($match[1])).'/';
}
}, $x);
echo $x;
Output
i-love-you/i-love-her/you-love-me/you--love--me
And the smallified version of it:
$x = " i love you/i love her/you love me/you love me ";
echo preg_replace_callback('/([^\/]+)\/(\1)?/',function($m){return isset($m[2])?str_replace(' ','-',trim($m[1])).'/'.str_replace(' ','--',trim($m[2])):str_replace(' ','-',trim($m[1])).'/';},$x);
I need to edit all odd words to upper case.
Here is sample of imput string:
very long string with many words
Expected output:
VERY long STRING with MANY words
I have this code, but it seams to me, that I can do it in better way.
<?php
$lines = file($_FILES["fname"]["tmp_name"]);
$pattern = "/(\S[\w]*)/";
foreach($lines as $value)
{
$words = NULL;
$fin_str = NULL;
preg_match_all($pattern, $value, $matches);
for($i = 0; $i < count($matches[0]); $i = $i + 2){
$matches[0][$i] = strtoupper($matches[0][$i]);
$fin_str = implode(" ", $matches[0]);
}
echo $fin_str ."<br>";
P.S. I need to use only preg_match function.
Here's a preg_replace_callback example:
<?php
$str = 'very long string with many words';
$newStr = preg_replace_callback('/([^ ]+) +([^ ]+)/',
function($matches) {
return strtoupper($matches[1]) . ' ' . $matches[2];
}, $str);
print $newStr;
// VERY long STRING with MANY words
?>
You only need to match the repeating pattern: /([^ ]+) +([^ ]+)/, a pair of words, then preg_replace_callback recurses over the string until all possible matches are matched and replaced. preg_replace_callback is necessary to call the strtoupper function and pass the captured backreference to it.
Demo
If you have to use regular expressions, this should get you started:
$input = 'very long string with many words';
if (preg_match_all('/\s*(\S+)\s*(\S+)/', $input, $matches)) {
$words = array();
foreach ($matches[1] as $key => $odd) {
$even = isset($matches[2][$key]) ? $matches[2][$key] : null;
$words[] = strtoupper($odd);
if ($even) {
$words[] = $even;
}
}
echo implode(' ', $words);
}
This will output:
VERY long STRING with MANY words
You may don't need regex simply use explode and concatenate the string again:
<?php
function upperizeEvenWords($str){
$out = "";
$arr = explode(' ', $str);
for ($i = 0; $i < count($arr); $i++){
if (!($i%2)){
$out .= strtoupper($arr[$i])." ";
}
else{
$out .= $arr[$i]." ";
}
}
return trim($out);
}
$str = "very long string with many words";
echo upperizeEvenWords($str);
Checkout this DEMO
I need to replace and concat some values in a random string, i store the values in an array.
I.e.
$search = array('dog', 'tree', 'forest', 'grass');
$randomString = "A dog in a forest";
If one or more array values matches the random string then i need a replace like this:
$replacedString = "A #dog in a #forest";
Can someone help me?
Thx.
foreach (explode(' ', $randomString) as $word) {
$replacedString .= in_array($word, $search) ? "#$word " : "$word ";
}
echo $replacedString; // A #dog in a #forest
foreach($search as $word)
{
$randomString = str_replace($word,"#".$word,$randomString);
}
Not sure if I understand what you're trying to do correctly but have a look at str_replace() function
and try something like
foreach($search as $string)
{
$replacement[] = "#".$search;
}
$new_string = str_replace($search, $replacement, $randomString);
This should work for you:
$words = explode(" ", $randomString);
foreach($words as $word){
if(in_array($word, $search)){
$word = "#$word";
}
}
$replacedString = implode(" ", $words);
I have a string in php formatted like this:
http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb
where aaa... and bbb.... represent random characters and are random in length.
I would like to parse the string so that I am left with this:
http://bbbbbbbbbbbbbbb
In this case I wouldn't recommend regex but a simple substring or explode
$data = "http://aaaaaaaaaa/*http://bbbbbbbbbbb"
$parts = explode('*', $data);
echo $parts[1];
fin :)
You don't need regular expressions at all in this case:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
echo substr($str, strpos($str, 'http://', 1));
Hi This would help you to get the address:
$str = 'http://www.example.com/*http://www.another.org/';
$pattern = '/^http:\/\/[\.\w\-]+\/\*(http:\/\/.+)$/';
//$result = preg_replace($pattern, '$1', $str);
$found = preg_match_all($pattern, $str, $result);
$url = (!$found==0) ? $result[1][0] : '';
echo $str . '<br />' . $url;
Here is the regular expression way:
$str = 'http://aaaaaaaaaa/*http://bbbbbbbbbbbbbbb';
$url = preg_replace("/^.*(http:\/\/.*[^(http:\/\/)+])$/", "$1", $str);
echo $url;
Here is a clean solution: grab everything after the last occurrence of "http://".
$start = strrpos($input, 'http://');
$output = substr($input, $start);
I want to know how to count to the second space then return to the newline with php , for example :
the text: "How are you?"
becomes
"how are
you?"
how can I do that with php?
thank you
Here is a function that uses strpos to return the position of the Nth specified character.
http://us2.php.net/manual/en/function.strpos.php#96576
Find that position, then do a substr_replace to put a \n in that spot.
print preg_replace('/((:?\S+\s){2})/i', "\$1\r\n", "How are you?" );
function addNlToText($text) {
$words = explode(' ', $text);
$out = '';
foreach ($words as $key => $value) {
$out .= $value;
if ($key % 2 === 0) {
$out .= "\n";
} else {
$out .= ' ';
}
}
return trim($out);
}
That's dirty, but it does what you ask...
$text = 'Hello, how are you?';
addNlToText($text); // "Hello, how\nare you?"
$text = 'Hello';
addNlToText($text); // "Hello"
$text = 'Hello what is going on?';
addNlToText($text); // "Hello what\nis going\non?"
I wonder if you are not after something like the wordwrap function?
http://www.php.net/wordwrap
Try this:
<?php
$mystring = 'How are you?';
$findme = ' ';
$pos = strpos($mystring, $findme);
$pos = strpos($mystring, $findme, $pos+1);
$mystring = substr_replace($mystring, '<br>', $pos, 0);
echo $mystring;
?>
You can do it using javascript, Is it ok using javascript?