I'm having trouble using strpos correctly. if I search for<br /> it will find it. If I search for <br /><br /><br /> with or without space between, it won't and using htmlspecialchars I can tell the string is full of it.
<?php
$picArray = glob('projectData/' . $data['folder'] . '/*.jpg',GLOB_BRACE);
$text = nl2br($data['definition']).'<br />';
$cutP = 0;
foreach($picArray AS $insert) {
if(strpos($text,'<br /> <br /> <br />',$cutP) !== FALSE){
$cutP = strpos($text,'<br /> <br /> <br />',$cutP)+6;
echo $cutP.'_';
$str_to_insert = '<img class="inTextImg" title="int" src="'.$insert.'" />';
$text = substr($text, 0, $cutP) . $str_to_insert . substr($text, $cutP);
}
else {
echo 'haha';
$text .= '<img class="inTextImg" title="outText!" src="'.$insert.'" />';
}
}
?>
Thank your for your ideas.
This is because nl2br keeps the original line break characters in place, just after the '<br />'. You need to include the line break characters in the string to search for. Since there can be a few different patterns for this it's easiest to use a regexp to match it:
$text = preg_replace('/(?:<br \/>\r?\n?){3}/', $str_to_insert, $text);
Have you tried using preg_match() ?
if(preg_match("\(<br />)+\",$text) > 0){
// code
}
Not 100% on the regex, but you would want one that checks for one or more br tags
Related
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.
I have the following code:
$data = "Normal text
    code
    code
    code
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value){
if(preg_match('/^    /',$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
    code
    code
    code
Normal text";
$data = nl2br($data);
$data= explode('<br />', $data );
foreach($data as $value)
{
if(preg_match('/^    /', 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
I am at a loss on why my PHP code, the preg_match, is not accepting input from an HTML textarea input when it has parentheses or returns:
Here is the relevant PHP:
/* Check for Ingredient Description */
if (preg_match ('%^\s*[A-Za-z0-9\,\.\' \-\"\(\)]{30,2048}$%', stripslashes(trim($_POST['ingredient_descrip']))))
{
$idscr = escape_data($_POST['ingredient_descrip']);
}
else
{
$idscr = FALSE;
echo '<p><font color="red" size="+1">
Please enter an ingredient description!</font></p>';
}
The custom function escape_data is as follows:
$dbc = mysql_connect (DBHOST, DBUSER, DBPW)
function escape_data ($data)
{
if (function_exists('mysql_real_escape_string'))
{
global $dbc;
// Need the connection.
$data = mysql_real_escape_string (trim($data), $dbc);
$data = strip_tags($data);
}
else
{
$data = mysql_escape_string (trim($data));
$data = strip_tags($data);
}
// Return the escaped value.
return $data;
}
Here is the relevant HTML that calls for the textarea input:
<form action="ingredient_form.php" method="post" enctype="multi-part/form-data">
<fieldset>
<p><b>Ingredient Description:</b></p>
<p><textarea cols="100" rows="20" name="ingredient_descrip"></textarea><?php if (isset($_POST['ingredient_descrip'])) echo $_POST['ingredient_descrip']; ?></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit Proposed Ingredient Profile" /></div>
<input type="hidden" name="submitted" value="TRUE" />
I have tried removing the preg_match and just accepting the textarea input, then using preg_replace function to regain formatting and test with the following code:
if ($_POST['ingredient_descrip'])
{
$idscr = stripslashes(trim($_POST['ingredient_descrip']));
echo "<p>" .$idscr. "</p>";
$idscr = escape_data($idscr);
echo "<p>" .$idscr. "</p>";
$idscrp = preg_replace("/[\r\n]+/", "<br />", $idscr);
echo "<p>" .stripslashes($idscrp). "</p>";
}
The preg_replace doesn't seem to be doing its job either. I put this into the textarea for testing purposes:
This is a (test)
Why isn't it working?
but
My echo results come back as:
This is a (test) Why isn't it working? but
This is a (test) \r\nWhy isn\'t it working? \r\nbut
This is a (test) rnWhy isn't it working? rnbut
The preg_replace should be substituting the \r\n with a break and then the stripslashes should get rid of the remainin escape characters. What am I missing?
Use nl2br() to replace new lines with <br /> tags, instead of trying to reinvent the wheel with preg_replace().
That said, your preg_replace() call works for me:
$str = <<<STR
foo
bar
baz
STR;
var_dump($str);
$str = preg_replace("/[\r\n]+/", "<br />", $str);
var_dump($str);
Output:
string(11) "foo
bar
baz"
string(21) "foo<br />bar<br />baz"
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))
I have a little script that replace some text, that come from a xml file, this is an example:
<b>Hello world,</b>
<include file="dynamiccontent.php" />
<img src="world.png" />
a lot of <i>stuff</i>
Obviosly the string is much more longer, but I would like to replace the <include
file="*" /> with the content of the script in the filename, at time I use an explode that find
<include file="
but I think there is a better method to solve it.
This is my code:
$arrContent = explode("<include ", $this->objContent->content);
foreach ($contenuto as $piece) { // Parsing array to find the include
$startPosInclude = stripos($piece, "file=\""); // Taking position of string file="
if ($startPosInclude !== false) { // There is one
$endPosInclude = stripos($piece, "\"", 6);
$file = substr($piece, $startPosInclude+6, $endPosInclude-6);
$include_file = $file;
require ($include_file); // including file
$piece = substr($piece, $endPosInclude+6);
}
echo $piece;
}
I'm sure that a regexp done well can be a good replacement.
Edited to allow multiple includes and file checking.
$content = '<b>Hello world,</b>
<include file="dynamiccontent.php" />
<img src="world.png" />
a lot of <i>stuff</i>';
preg_match_all('!<include file="([^"]+)" />!is', $content, $matches);
if(count($matches) > 0)
{
$replaces = array();
foreach ($matches[1] as $file)
{
$tag = '<include file="'.$file.'" />';
if(is_file($file) === true)
{
ob_start();
require $file;
$replaces[$tag] = ob_get_clean();
}
else
{
$replaces[$tag] = '{Include "'.$file.'" Not Found!}';
}
}
if(count($replaces) > 0)
{
$content = str_replace(array_keys($replaces), array_values($replaces), $content);
}
}
echo $content;
So you wanna know what the value of the attribute file of the element include? Try:
$sgml = <<<HTML
<b>Hello world,</b>
<include file="dynamiccontent.php" />
<img src="world.png" />
a lot of <i>stuff</i>
HTML;
preg_match('#<include file="([^"]+)"#',$sgml,$matches);
print_r($matches[1]); // prints dynamiccontent.php
If not, please Elaborate.
/(?<=<include file=").+(?=")/
matches "dynamiccontent.php" from your input string