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?
Related
My code below is working
<?php
//load synonyms of words
$json_file = fopen("dict.json", "r") or die("Unable to open file!");
$js = fread($json_file, filesize("dict.json"));
$json = json_decode($js, true);
$text = "Hello my friend, today i am feeling good.";
$ar_text = explode(" ", $text);
foreach ($ar_text as $val)
{
$rand = rand(1, 3);
$randx = rand(1, 3);
if ($rand == $randx)
{
if (array_key_exists($val, $json))
{
$null = "{" . $val . "|";
$inc = $json[$val]['sinonim'];
$i = 1;
foreach ($inc as $siap)
{
$null .= $siap . "|";
if ($i == 4) break;
$i++;
}
$null .= "}";
$text = str_replace(" $val ", " $null ", $text);
//echo $null."<br>";
}
else
{
//echo "not found ".$val."<br>";
}
}
//echo $val;
}
$text = str_replace("|}", "}", $text);
echo $text;
//echo $json['mengaras']['tag'];
?>
i use explode to get word by word and then replace with word synonyms, how to get a phrase like "really good" and find it on dict.json.
Example: Hello, i am really good right now.
Output: Hello, i am {so fine|super fine|superb} now.
Use str_replace() - Replace all occurrences of the search string with the replacement string
$text = "Hello, i am really good right now.";
$find = "really good";
$replace = "so fine|super fine|superb";
$newtext= str_replace($find, $replace, $text);
OUTPUT:
Hello, i am so fine|super fine|superb right now.
You can do it this way too:
$text = 'Hello, i am really good right now.';
$match = 'really good';
$match_len = strlen($match);
$replace = array("so fine","super fine", "superb");
$pos = strpos($text, $match);
if($pos !== false){
echo "Word Found!";
$replace = implode("|", $replace);
$embed = '{' . $replace . '}';
echo $text_before . ' ' . $embed . ' ' . $text_after;
} else{
echo "Word Not Found!";
}
Output
Hello, i am {so fine|super fine|superb} right now.
am trying to replace a word in a string BUT i want to get the word found in the function and replace it with a word with stars with the exact length ?
Is this possible or do i need to do this in some other way ?
$text = "Hello world, its 2018";
$words = ['world', 'its'];
echo str_replace($words, str_repeat("*", count(FOUND) ), $text);
You could use a regular expression to do that :
$text = preg_replace_callback('~(?:'.implode('|',$words).')~i', function($matches){
return str_repeat('*', strlen($matches[0]));
}, $text);
echo $text ; // "Hello *****, *** 2018"
You also could secure this using preg_quote before to use preg_replace_callback() :
$words = array_map('preg_quote', $words);
EDIT : The following code is another way, that use a foreach() loop, but prevent unwanted behaviors (replacing part of words), and allows multi-bytes characters:
$words = ['foo', 'bar', 'bôz', 'notfound'];
$text = "Bar&foo; bAr notfoo, bôzo bôz :Bar! (foo), notFOO and NotBar or 'bar' foo";
$expt = "***&***; *** notfoo, bôzo *** :***! (***), notFOO and NotBar or '***' ***";
foreach ($words as $word) {
$text = preg_replace_callback("~\b$word\b~i", function($matches) use ($word) {
return str_ireplace($word, str_repeat('*', mb_strlen($word)), $matches[0]);
}, $text);
}
echo $text, PHP_EOL, $expt ;
Another approach:
$text = "Hello world, its 2018";
$words = ['world', 'its'];
$f = function($value) { return str_repeat("*", strlen($value)) ; } ;
$replacement = array_map($f, $words);
echo str_replace($words, $replacement, $text);
You can try this :
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018
Is it what you are looking for?
You can go like this..
$text = "Hello crazy world, its 2018";
$words = ['world', 'its'];
array_walk($words,"replace_me");
function replace_me($value,$key)
{
global $text;
$text = str_replace($value,str_repeat("*",strlen($value)),$text);
}
echo $text;
$text = "Hello world, its 2018";
$words = ['world', 'its'];
// Loop through your word array
foreach ($words as $word) {
$length = strlen($word); // length of the word you want to replace
$star = str_repeat("*", $length); // I build the new string ****
$text = str_replace($word, $star, $text); // I replace the $word by the new string
}
echo $text; // Hello *****, *** 2018
I am trying to remove all leading and trailing <br> in a string using PHP.
Here is an example
<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>
I want to return
Hello<br>
World<br>
<p>This is a message<br>...</p>
I tried to do the following
echo trim($str, '<br>');
But it does not remove them. How can I remove the new line html code?
Use preg_replace with the beginning ^ and end $ anchors:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);
Or for multiple lines:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);
You could also trim() it multiple times:
while($string !== ($string = trim($string, '<br>'))){}
This function does the job. Also applicable to anything else really.
//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
if(!$h = trim($h,$n)){
trimAll($h, $n);
}
return $h;
}
I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:
any tabs
any new lines
any
any
any tabs
any new lines
function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
if( ! is_array($myList) ){
$charsToTrim[] = $chr;
} else {
$charsToTrim = $myList;
}
foreach($charsToTrim as $chr){
$len = strlen($chr);
$nlen = $len * -1;
while( substr($str, 0, $len) == $chr){
$str = trim(substr($str, $len));
}
while( substr($str, $nlen) == $chr){
$str = trim(substr($str, 0, $nlen));
}
}
return $str;
}
to use
// default use case
echo trimString($message);
or
//remove only one string
echo trimString($message, '<br>'); // remove only the leading training '<br>'
or
//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );
I hope this helps someone out there :)
$p=array(
'<br><br>',
'Hello<br>',
'World<br>',
'<p>This is a message<br>...</p>',
'<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
$parts=explode($sub, $str);
for ($x=0; $x<2; $x++) {
foreach ($parts as $i=>$v) {
if (!strlen($v)) {
unset($parts[$i]);
} else {
break;
}
}
$parts=array_reverse($parts);
}
return implode($sub,$parts);
}
foreach ($p as $str) {
print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}
I want to remove words from sentence if word contains #, I am using php.
Input: Hi I am #RaghavSoni
Output: Hi I am
Thank You.
You could do:
$str = preg_replace('/#\w+/', '', $str);
This is not a good way, but it works :
<?php
$input="Hi I am #RaghavSoni";
$inputWords = explode(' ', $input);
foreach($inputWords as $el)
{
if($el[0]=="#" )
{
$input = str_replace($el, "", $input);
}
}
echo $input;
?>
while(strpos($string, '#') !== false) {
$location1 = strpos($string, "#");
$location2 = strpos($string, " ", $location1);
if($location2 !== false) {
$length = $location2 - $location1;
$string1 = substr($string, 0, $location1);
$string2 = substr($string, $location2);
$string = $string1 . $string2;
}
}
echo $string;
echo str_replace("#RaghavSoni", "", "Hi I am #RaghavSoni.");
# Output: Hi I am.
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);