Replace 2 \n in text to <br \> in php? - php

i know the nl2br function in php to replace '\n' to <br \>,
but how to replace \n\n to <br \>.
for example:
string=
'paragraph
1
paragraph2'
it is expected to show
paragraph1
paragraph2
p.s. i have a form to input the text.
Any help is most appreciated :)

Replace it easily with some simple regex:
preg_replace('/\n+/', '<br/>', $string);

try this
$string=
'paragraph
1
paragraph2';
$arr_temp = explode("\n", $string);
$prev_blank = false;
foreach($arr_temp as $str)
{
if(trim($str)=="")
{
if(!$prev_blank)
{
echo "<br/>";
$prev_blank = true;
}
}
else
{
echo trim($str);
$prev_blank = false;
}
}
output:
paragraph1
paragraph2

i've solved the problem.
just use
str_replace("\n\r\n", "<br />", $model->solutionText);

Related

Replace string between two char(special symbol) in php

I have a string like: He *is* a good boy. How *are* you. Then I want to replace is and are with input type textbox means replace things between asterisk(*). How can I get this Please help me out.
<?php
$buffer = 'He *is* a good boy. How *are* you.';
echo "Before: $buffer<br />";
$buffer = preg_replace_callback('/(\*(.*?)\*)/s', 'compute_replacement', $buffer);
echo "After: $buffer<br />";
function compute_replacement($groups) {
// $groups[1]: *item*
// $groups[2]: item
return '<input type="text" value="'.$groups[2].'" />';
}
?>
The result:
try this,
<?php
$x="hai, *was/is* are you, is this *was* test ";
echo preg_replace("/\*[\w\/]*\*/","",$x);
?>
Use preg_replace(); e.g:
<?php
$pattern = '/\*\w+\*/';
$string = 'he *is* a good boy';
$replacement = 'was';
echo preg_replace($pattern, $replacement, $string);
Yields:
he was a good boy
Try in this way:
$txt = "He *is* a good boy. How *are* you.";
$_GET['one'] = "doesn't";
$_GET['two'] = "think about";
preg_match_all( '{\*[^*]+\*}',$txt,$matches );
$txt = str_replace( $matches[0][0], $_GET['one'], $txt );
$txt = str_replace( $matches[0][1], $_GET['two'], $txt );
echo $txt;
3v4l.org demo
or, with preg_replace, in this way:
$txt = preg_replace
(
'/^(.*)\*[^*]+\*(.*)\*[^*]+\*(.*)$/', # <-- (Edited)
"\\1{$_GET[one]}\\2{$_GET[two]}\\3",
$txt
);

automatic convert word to link in PHP

I want write a simple code that convert special words to special link (for wiki plugin), if it's not a link!
For example suppose we have a text "Hello! How are you?!" and
we want convert are to are, but if we have Hello! How are you?! or Hello! How are you?! does not change. Because it's a link.
How can I do it in PHP?! With preg_replace?! How to?
Thanks.
It's easy.
<?php
$string = "Hello! How are you?!";
$stringTwo = "Hello! how are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)/", $string);
}
echo turnTheWordIntoALink($string, 'are', 'http://google.com');
echo turnTheWordIntoALink($stringTwo, 'are', 'http://google.com');
Output:
First function output: Hello! How are you?!
Second function output: Hello! how are you?!
Alternative:
If you want to not detect <a> tags which were closed, you can use this alternative code:
$stringThree = "Hello! how <a href=\"#\">are you?!";
function turnTheWordIntoALink($string, $word, $link) {
if(isLink($string)) {
return $string;
} else {
$string = str_replace($word, "" . $word . "", $string);
return $string;
}
}
function isLink($string) {
return preg_match("/(<a href=\".\">)+(.)+(<\/a>)/", $string);
}
echo turnTheWordIntoALink($stringThree, 'are', 'http://google.com') . "\n";
This gives the output: Hello! how <a href="http://google.com">are you?!
this code is about : if there is a some URL in some phrase it will convert to a link
$word = 'hello how are you google.com, wish you good time';
$prg = "/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
if(preg_match($prg, $word, $url))
{
echo preg_replace($prg, "<a href=http://$url[0]>{$url[0]}</a>", $word);
}
else
{
echo $word;
}
To better clarify the issue:
I have a HTML code that have some tags. I want some words in that, converted to some links. But if it is a another link does not convert. See below advanced example for special word you that we want linked to the google:
This is a sample text.
Hello?! How are you?!
Are you ready?!
should be convert to:
This is a sample text.
Hello?! How are you?!
Are you ready ?!
Note that the first you changed, but that second you was not changed, because it's in the another <a> tag.
Answer:
Because of this work has issue with regular expression, this problem can solve without regular expression. Here a simple solution is given:
$data = 'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text. <br/>'.
'Hello! This is a sample text.';
$from = " is ";
$to = '<a href="http://www.google.com" > '.$from.' </a>';
echo $data;
$data = explode($from, $data);
echo "<br><br>";
echo $data[0];
$diff = 0;
for($i=1; $i<count($data); $i++){
$n = substr_count($data[$i-1], '<a ') + substr_count($data[$i-1], '<A ');
$m = substr_count($data[$i-1], '</a>') + substr_count($data[$i-1], '</A>');
$diff += $n-$m;
if($diff==0)
echo $to.$data[$i];
else
echo $from.$data[$i];
}

How to remove part of a string, that's wrapped in <b></b>, with php? [duplicate]

This question already has an answer here:
DOM php delete all tags by tag name
(1 answer)
Closed 7 years ago.
So I have a text being pulled from db:
<b>Object title</b>
<br />
<p>Object description</p>
and I need to remove <b>Object title</b>, I tried using substr, but didn't quite come up with the correct way of putting it together. Can you please show me how I could do that?
Edit
Please note: I need to remove only the first <b></b> element, every other bold part of that string should stay the way it is.
u shoud use preg_match for this problem.
$text = "<b>Object title</b><br /><p>Object description</p>";
if (!preg_match("/<b>.*<\/b>/",$text,$m)) {
str_replace($m[0],"",$text);
}
this should work for u.
if u want remove all u can run a a loop on $m.
This can be obtained without the use of regex as well.
We are using simple PHP string functions here:
Try this:
<?php
function removeTags($subject, $replaceStr){
$strlength = strlen($replaceStr);
$subject = strstr($subject, $replaceStr, true) . substr(strstr($subject, $replaceStr), 0 + $strlength);
return $subject;
}
$str = '<b>Object title</b><b>Object title</b><br /><p>Object description</p><b>Object title</b>';
$brOpenRemoved = removeTags($str, '<b>');
$brCloseRemoved = removeTags($brOpenRemoved, '</b>');
echo $brCloseRemoved; // final output
?>
The function removeTags removes the string provided to it. We have provided tags here.
It only removes first occurrence because we are using functions like strstr() which only work on first occurence of the string.
EDIT
We can use below function to prevent calling the same function again and again
<?php
function removeFirstOccurence($subject, $replaceTag){
$replaceStrings = ['<'.$replaceTag.'>', '</'.$replaceTag.'>'];
foreach($replaceStrings as $replaceStr){
$strlength = strlen($replaceStr);
$subject = strstr($subject, $replaceStr, true) . substr(strstr($subject, $replaceStr), 0 + $strlength);
}
return $subject;
}
$str = '<b>Object title</b><b>Object title</b><br /><p>Object description</p><b>Object title</b>';
$brRemoved = removeFirstOccurence($str, 'b');
echo $brRemoved; // final output
?>
If you are sure that there is your pattern in the text:
//remove first <b> tag
$text = '<b>foo</b>...';
$pos = strpos($text,'<b>');
if ($pos !== false) {
$newtext = substr_replace($text,'',$pos,strlen('<b>'));
}
//remove first </b> tag
$pos = strpos($text,'</b>');
if ($pos !== false) {
$newtext = substr_replace($newtext,'',$pos,strlen('</b>'));
}
You can use $limit to the maximum possible replacements for each pattern in preg_replace
$yourString =
"<b>Object title</b>
<br />
<p>Object description</p>";
$limit = 1;
$pattern = "/<b>(.*)<\/b>/";
$replace = "";
$newString = preg_replace($pattern, $replace, $yourString, $limit);
echo $newString;
output:
<br />
<p>Object description</p>
If you use (.*) you can also delete <b> and </b> tags and just stay with the content:
$limit = 1;
$pattern = "/<b>(.*)<\/b>/";
$replace = "$1";
$newString = preg_replace($pattern, $replace, $yourString, $limit);
echo $newString;
output:
Object title
<br />
<p>Object description</p>
Or keep only tags without content:
$limit = 1;
$pattern = "/<b>(.*)<\/b>/";
$replace = "<b></b>";
$newString = preg_replace($pattern, $replace, $yourString, $limit);
echo $newString;
output:
<b></b>
<br />
<p>Object description</p>

PHP Regular Expression: String starts with and ends with

$ptn = "/^Response.+?[:] /";
$str = "Response from Moore Auto: Thanks for your feedback";
$rpltxt = "";
echo preg_replace($ptn, $rpltxt, $str);
"Moore Auto" is a variable name, so I simply need the text after the colon and space. Desired final result would be the string "Thanks for your feedback" in this case. Much appreciated!
Simple with substr() , like this:
$str = 'Response from Moore Auto: Thanks for your feedback';
echo substr($str, strpos($str,':')+2); //echoes "Thanks for your feedback"
Damiens solution does not work, if there is more than one colon. This should always work if the first part doesn't contain a colon:
<?php
$ptn = "/^Response[^:]+:\s*(.*)$/";
$str = "Response from Moore Auto: Thanks for your feedback";
if (preg_match($ptn, $str, $match)) {
$text = $match[1];
echo $text; //Thanks for your feedback
}
?>
try
<?php
$ptn = "/^(Response.+[:])(.*?)/";
$str = "Response from Moore Auto: Thanks for your feedback";
$rpltxt = "$2";
echo preg_replace($ptn, $rpltxt, $str);
?>

PHP preg_match? How to return not matched characters?

Lets say i have:
$string = 'qwe1ASD#';
if(preg_match('/^[a-zA-Z]+$/', $string))
{
echo 'OK';
}
else
{
echo 'BAD';
}
Now, is there simple solution, to find all characters from $string which don't match expression? So in return, in place of "BAD" i want to have ex. "BAD. You can't use following characters: 1#"
Thanks in advance for any simple hints! :)
Thank you Floern, your answer suit best my needs. It have only one "preg" so it's also good for performance. Thank you again.
I implemented it for now as follw:
if(preg_match_all('/[^a-zA-Z0-9]/s', $string, $forbidden))
{
$forbidden = implode('', array_unique($forbidden[0]));
echo 'BAD. Your string contains forbidden characters: '.htmlentities($forbidden).'';
}
$tmpstring=preg_replace('~[A-Za-z]~','',$string);
if(strlen($tmpstring))
//bad chars: $tmpstring
You could use preg_match_all():
if(preg_match_all('/[^a-zA-Z]/s', $string, $matches)){
var_dump($matches); // BAD
}
else{
echo 'OK';
}
$string = 'qwe1ASD#';
if(preg_match('/^[a-zA-Z]+$/', $string))
{
echo 'OK';
}
else
{
echo 'BAD. You cannot use the following characters: ' + preg_replace('/[a-zA-Z]/', '', $string);
}
There are different ways. I find this one nice:
$check = preg_prelace('/[a-zA-Z]/', '', $string);
if ($check) echo 'BAD ' . $check;
UPDATE:
if (strlen($check)) echo 'BAD ' . $check;

Categories