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";
}
Related
i want search string in text file. find result and return after : character.
input is alex
text file include this item
alex:+123
david:+1345
john:+1456
output is +123
$input = "alex";
file_get_contents("TextFilePath");
//in this step i don't know what should i do
Maybe not the best solution, but you can use file and loop on the array. explode each line to see if the needle was present.
function findInAFile($filename, $needle) {
// read file split on newline
$lines = file($filename);
// check each line and return first occurence
foreach ($lines as $line) {
$arr = explode($needle, $line, 2);
if (isset($arr[1])) {
return $arr[1];
}
}
}
echo findInAFile('file.txt', $input.':');
You can use a regular expression match to locate lines beginning with the given input:
$input = "alex";
$text = file_get_contents("TextFilePath");
if (preg_match('#^' . preg_quote($input) . ':(.*)#m', $text, $match) {
// Found input
var_dump($match[1]);
}
need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
You can use the preg_match:
For example:
preg_match("/type-(.\w+)-id-(.\d+)/", $input_line, $output_array);
To check, you may need the service:
http://www.phpliveregex.com/
P.S. If the function preg_match will be too heavy, there is an alternative solution:
$str = 'IDlocationTagID-type-area-id-492';
$itr = new ArrayIterator(explode('-', $str));
foreach($itr as $key => $value) {
if($value === 'type') {
$itr->next();
var_dump($itr->current());
}
if($value === 'id') {
$itr->next();
var_dump($itr->current());
}
}
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
You can use explode to get the values:
$a = "IDlocationTagID-type-area-id-492";
$data = explode("-",$a);
echo "Area ".$data[2]." Id ".$data[4];
$matches = null;
$returnValue = preg_match('/type-(.*?)-id/', $yourString, $matches);
echo($matches[1]);
Say I have string such as below:
"b<a=2<sup>2</sup>"
Actually its a formula. I need to display this formula on webpage but after b string is hiding because its considered as broken anchor tag. I tried with htmlspecialchars method but it returns complete string as plain text. I am trying with some regex but I can get only text between some tags.
UPDATE:
This seems to work with this formula:
"(c<a) = (b<a) = 2<sup>2</sup>"
And even with this formula:
"b<a=2<sup>2</sup>"
HERE'S THE MAGIC:
<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
if($index != $open_sup && $index != $close_sup)
{
if($char == "<")
{
echo "<";
}
else{
echo $char;
}
}
else{
echo $char;
}
}
OLD SOLUTION (DOESN'T WORK)
Maybe this can help:
I've tried to backslash chars, but it doesn't work as expected.
Then i've tried this one:
<?php
$string = "b<a=2<sup>2</sup>";
echo $string;
?>
Using < html entity it seems to work if i understood your problem...
Let me know
Probably you can give spaces such as :
b < a = 2<sup>2</sup>
It does not disappear the tag and looks much more understanding....
You could try this regex approach, which should skip elements.
$regex = '/<(.*?)\h*.*>.+<\/\1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
return htmlentities($match[2]);
}, $string);
echo $string;
Output:
b<a=2<sup>2</sup>
PHP Demo: https://eval.in/507605
Regex101: https://regex101.com/r/kD0iM0/1
I am trying to create a regex to replace a string. Here is my pattern:
\{mailMerge: details_activity_number\\}
When I do a search like this on a string like this:
hello {mailMerge: details_activity_number\}world
its fine. But, if there's a line break like this:
hello \{
mailMerge: details_activity_number\} world
it breaks. Here is my code in PHP:
$pattern = '\{mailMerge: 'mailMerge: details_activity_number'\}';
$content = str_replace($pattern, $value, $content);
Can anyone help me with creating a pattern that would take into consideration possible line breaks/white spaces/etc to guarantee a match?
thanks
EDIT
private function findAndReplace($content, $mergedArray){
$test=$content;
try{
foreach($mergedArray as $ArrayKey => $ArrayValue){
foreach ($ArrayValue as $key => $value) {
$pattern = "\{\s*mailMerge:\s+". $key ."\s*\\\}";
if($value){
$test = preg_replace($pattern, $value, $test);
}else{
$test = preg_replace($pattern, "No Value Exists", $test);
}
}
}
}catch(Exception $e){
throw $e;
}
return $test;
}
The first version that you posted doesn't allow for any space between { and m. You need to do something like this:
\{\s*mailMerge:\s+details_activity_number\s*\\\}
The \s* means "match zero or more spaces (or other white space, like new lines) here." \s+ means "match one or more spaces (or other white space, like new lines) here."
NOTE: Your code above uses str_replace, but you are trying to do a regex replace. You need to use preg_replace instead of str_replace, like in this code:
$content = "\{mailMerge: 'mailMerge: details_activity_number'\}";
$content = preg_replace('/\{\s*mailMerge:\s+details_activity_number\s*\\\}/m', $value, $content);
EDIT BASED ON COMMENTS: Try this; it is working for me.
$value = "foo barrrrrr";
$content = "hello
{mailMerge: details_activity_number\} world";
$content = preg_replace("/\\\\?\\{\s*mailMerge:\s+details_activity_number\s*\\\\?\\}/m", $value, $content);
echo $content; // produces "hello foo barrrrrr world"
Is there a way I can check if a user enters a <p> tag inside a form using PHP?
If you simply want to strip all markup use:
strip_tags ( string $str [, string $allowable_tags ] )
otherwise:
substr_replace ( $string , string $replacement , int $start [, int $length ] )
Depends on why you what to know
1 - PHP.net
If it is posted, you can do something like strstr of '<p>' or one of the similar functions, which will then return the location if it exists or NULL if it doesn't.
<?php if ( strstr ( $body, '<p>' ) == NULL )
echo 'All Clear';
else die ( 'Contains <p>' );
if(empty($_POST['foo'])) {
print "Foo empty";
} else {
if(stristr($_POST['foo'], '<p>')) {
print "Contains P tag";
} else {
print "No P tag";
}
}
You could use javascript or jquery .onFocus event.
Assuming they don't enter anything fancy like <p class="stuff">, you can use a simple strpos() call:
$text = $_POST['name_of_field'];
if (strpos($text, '<p>') !== FALSE) {
die("No <p> tags allowed");
}
If they enter attributes, then you'd most likely need a regex, which has its own basket of problems:
$text = $_POST['name_of_field'];
if (preg_match('/<p.*?>/i', $text)) {
die("No <p> tags allowed");
}
Is this what you mean? Assuming you have the form content in a string variable, something like this should work:
<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL | E_STRICT);
$string1 = 'Hello <p> world';
$string2 = 'Hello world';
$foundIt1 = strripos($string1, '<p>');
$foundIt2 = strripos($string2, '<p>');
if (false === $foundIt1) {
echo '1. didn\'t find it';
} else {
echo "1. found it at offset $foundIt1";
}
echo "\n";
if (false === $foundIt2) {
echo '2. didn\'t find it';
} else {
echo "2. found it at offset $foundIt2";
}
?>
If you want to replace or remove them:
$new_data = preg_replace("/<p>/", "whatever you want to replace it with here", $_POST['form_field_id_here']);
If you just want to check for them
strpos("<p>", $_POST['form_field_id_here']);
Then read this to make sure you aren't leaving your site open to attackers:
What's the best method for sanitizing user input with PHP?
(Edit: I know, I know. No regex for HTML parsing. IMHO, if all you are doing is checking for tags then a little bit of regex is better than using a huge HTML parser. That said, if you are checking for many tags and things like <p class="something"> then you should look at this: http://docs.php.net/manual/en/domdocument.loadhtml.php )