PHP: preg_match not working - php

I have the following code:
$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value){
if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/',$value)){
echo 'code';
echo '<br />';
}else{
echo 'Not code';
echo '<br />';
}
}
I want to check if each of the lines starts with 4 spaces and if it does i want to echo as 'Code' and if it doesn't i want to echo as 'Not code'. But i am getting the output as 'Not code' though the 2nd , 3rd and 4th lines start with four spaces. I cannot figure out what I have done wrong. Please help me.

nl2br doesn't generate <br /> unless you tell it to. Your explode logic is wrong.
Instead, try this:
$data = "Normal text.......";
foreach(explode("\n",$data) as $line) {
// your existing foreach content code here
}

got it working
added a trim() to get rid of the newline in front of the string
nl2br replace \n with <br />\n (or <br />\r\n),
so when spliting on <br /> the \n is left as the first char
<?php
$data = "Normal text
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
&nbsp&nbsp&nbsp&nbspcode
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value)
{
if(preg_match('/^&nbsp&nbsp&nbsp&nbsp/', trim($value)))
{
echo 'code';
}
else
{
echo 'Not code';
}
echo '<br />';
}
?>

You could also use "startsWith" as defined here...
https://stackoverflow.com/a/834355/2180189
...instead of the regexp match. That is, if the spaces are always at the beginning

Related

Replace strings in php

I have a string that consists of tags <p> </p> and I want to replace them by <br />, but whenever I try using str_replace() it does not do so.
Is there any solution to it? Any other possible way to do it?
$string="<p> This is one para </p> <p> This is second </p>";
Using:
str_replace("</p> <p>","<br />",$string> nothing gets replaced.
Are you looking for something like this?
<?php
$string = "<p> This is one para </p> <p> This is second </p>";
$searchArray = array(
'<p>'
, '</p>'
);
$replaceArray = array(
''
, '<br />'
);
var_dump( str_replace($searchArray, $replaceArray, $string) );
?>
Output
string(47) " This is one para <br /> This is second <br />"
str_replace looks for an exact match, and replaces it. There is no "<p> </p>" in your string, and so it will never match. The behaviour you seem to be expecting is this:
If the string contains these substrings, replace them with this. Even if str_replace did behave that way, how would it know where to put the replacement?
I believe this is your intent;
$needles = array("<p>" => "",
"</p>" => "</br>");
$string = "<p> This is one para </p> <p> This is second </p>";
$match = true;
foreach($needles as $find => $replace)
{
if(strpos($string, $find) === false)
{
$match = false;
}
}
if($match)
{
foreach($needles as $find => $replace)
{
$string = str_replace($find, $replace, $string);
}
}
echo $string;
If the string matches all of the keys in $needles, it will replace them with the corresponding values in $needles. If you're going to be doing a lot more HTML manipulation however, then regular expressions using preg_replace would be a better approach.

Identify a blank line in a text area

I am trying to identify a blank lines in a string. Below is my attempt in PHP:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach($devices as $device) {
if(!empty($device)){
echo $device;
} else {
echo "end of value";
}
}
?>
When I input the following:
1
2
3
4
I get this output:
1
2
3
4
But what it should be outputting is this:
1
2
3
end of value
end of value
4
What am I doing wrong?
They probably contain a \r (which is posted on new lines in text areas for some browsers/OS'es), a space or a tab character. You can get rid of these by using the trim() command:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach ($devices as $device) {
$device = trim($device); //Trim that string!
if(!empty($device))
{
echo $device;
}
else
{
echo "end of value";
}
}
?>
Oh, and PLEASE indent your code for your own and everybody elses sake.
Alternatively, split up your string by using regex:
$devices = preg_split("/(\r\n|\n\r|\r|\n)/", $alldevs);
This should give you what you want:
if( trim($device) !== '' )
{
echo $device."<br>";
}
else
{
echo "end of value"."<br>";
}
Outputs:
1
2
3
end of value
4
I think your problem is with \r\n
Use this code
$alldevs = str_replace("\r", '', $alldevs);
Then explode it, and also use trim for clean spaces
$alldevs = trim($alldevs);
first, please read dealing with line endings and wikipedia newline
second, you are using string explode when you should use a function like preg_match_all
code should look something like this (mind the bad regex please):
<?php
$string = $_POST['devs'];
preg_match_all('%^([^\n\r]*)[\n\r]?$%im', $string, $matches);
foreach ($matches[1] as $match) {
if($match) {
var_dump($match);
} else {
echo 'empty line' . PHP_EOL;
}
}
adjust this code to fit your needs, i left a var_dump there so you could see the string length.
Add a check for a string with more than 0 characters,
if(!empty($device) && strlen($device)>0) {
I would also try a use case with \r\n on your line-breaks, you'll run into that as well.
you can try this
$devices = preg_replace('/^\s*$/','end of value',explode("\n",$alldevs));
foreach($devices as $device) {
echo $device, "\n";
}

Line break in PHP

I am trying to create a newline character in my foreach loop. After the URL I am trying to create a newline and then have a "------" between the title and content. After this there is supposed to be a space between the next URL. I have the space but I can't seem to get the line break. When I echo "\t" or "\n" in the loop nothing happens. When I use HTML in the loop it won't work, gives too many spaces.
for($i=0; $i < 4 ;$i++)
{
foreach ($json as $URL)
{
echo $URL ['results'][$i]['url'];
echo "---------------";
foreach ($json as $TITLE)
{
echo $TITLE ['results'][$i]['title'];
echo "--------";
}
foreach ($json as $content)
echo $content['results'][$i]['content'];
echo "---------------- ";
}
}
Is there a function in php besides "\n" or another way of manipulating the HTML to insert the line break?
TIA
There are two things you can do:
1: Use <br> as line break. If you use that, you should also consider using <hr> to insert the horizontal line.
some text<br>
<hr>
some other text<br>
2: Use <pre> and </pre> tags around your text to output preformatted text. You can then use \n and \t to format your text.
<pre>
some text\n
-------\n
some other text\n
</pre>
This might the one you are searching for
for($i=0; $i < 4 ;$i++)
{
foreach ($json as $URL)
{
echo $URL ['results'][$i]['url'];
echo "<br/>";
echo "---------------";
foreach ($json as $TITLE)
{
echo $TITLE ['results'][$i]['title'];
echo "--------";
}
foreach ($json as $content)
echo $content['results'][$i]['content'];
echo "---------------- ";
}
}
\n doesn't work in HTML. If you view source of the document you will however see the line breaks. Use html markup like
Test line break<br />
<p>paragraph</p>
<p>paragraph</p>
Simply add <br /> to echo statements. as in html we use this for line breaks.
echo "Content"."<br />";
This would give line breaks in HTML format.
use
echo "<br />";
instead of
echo "---------------- ";
Use echo '';
<?php
echo "first line.<br />Second line.';
?>
or nl2br() function,
<?php
echo nl2br("first line.\nSecond line.");
?>
You can consider
echo "<hr /> ";

echo text separating every 3 words per line?

I have seen some samples using var_dump, but I I would rather use a simple echo, if it's possible.
It should look like this using echo:
This is a
simple text
I just wrote
Using var_dump:
function split3($text)
{
$array = array();
foreach(explode(' ',$text) as $i=>$word)
{
if($i%3) {
$array[floor($i/3)] .= ' '.$word;
} else {
$array[$i/3] = $word;
}
}
return $array;
}
$text = "This is a simple text I just wrote";
var_dump(split3($text));
Your sample output is a bit wrong compare to your question.
If the output is like this.
This is a
simple text I
just wrote
Then replace the var_dump(split3($text)); with this
$splitedText = split3($text);
foreach($splitedText as $value){ //Just print the array content
echo $value . "<br />"; //I use <br /> as a new line
}

while-loops and if-statement trouble php

I want to be able to check wheter an inputted string has any of the characters in $alphabet and if it does display the relevant image per relevant character. so if someone entered hello. it would display h.png, e.png, l.png, l.png and o.png. So far I have got it to recognise the users input and echo it out and search whether it has a particular letter and output it to the relevant image via this code:
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
if(strcmp($input[0],'a')==0){
echo "<img src='egypt/$input.png'>";
}else{
echo "You did not write a";
}
?>
Which works perfectly. However I tried to input more code which would allow a whole string including spaces to be analysed against the whole alphabet $alphabet and match each character in the string to the right image with this code below: but it doesnt work
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
while (list(, $value) = each($alphabet) AND list(, $input) = each($value2)) {
if(strcmp($value2[0],$value)==0){
echo "<img src='egypt/$value2.png'>";
}else{
echo "You did not write a";
}
}
?>
Above is the neccessary code.
Update: I have worked out how to match the first letter of input against any in the alphabet but still struggling to work out how to map against a whole string with spaces.
<?php
$input = trim($_POST["textarea"]);
echo $input;
echo "<br />";
$alphabet = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
if(strcmp($input[0],$alphabet)==0){
echo "<img src='egypt/$input.png'>";
}else{
echo "Error";
}
?>
Code with reference to update for anyone who cares
Let me suggest you a different route.
$fos='hello world!';
$cucc=preg_replace('/([a-z])/', '<img src="$1.png" />', $fos);
This will replace every letter (a-z) with its img equivalent, so you will get this result:
<img src="h.png" /><img src="e.png" /><img src="l.png" /><img src="l.png" /><img src="o.png" /> <img src="w.png" /><img src="o.png" /><img src="r.png" /><img src="l.png" /><img src="d.png" />!
I'm not sure if this will solve your problem completely, but I noticed this right away:
while (list(, $value) = each($alphabet) AND list(, $input) = each($value2))
should be:
while (list(, $value) = each($alphabet) AND list(, $value2) = each($input))

Categories