PHP find string knowing only beginning of it - php

Hello i'm trying to find a the rest of the string knowing only the beginning of it.
Example:
I have start of string Dude=99999
Number 99999 changes its not always the same but word Dude is always the same.
So my question is how can i find the rest of the string after word Dude...
I know in linux there is something like t*.txt but in php? help please.
SHORT: find 'dude= and read the string until '

This sounds like a good match for a regex:
$regex = "/\'Dude=([0-9]+)\'/";
$str = "'Duck=123456' 'Chicken=982731' 'Dude=123487' 'Boat=129832'";
preg_match_all($regex, $str, $matches, PREG_SET_ORDER, 0);
echo $matches[0][1]; // prints: 123487
If your input string/text has line-breaks, you will probably need additional flags for the regex matcher. But there are already questions and answers for this available, so please refer to the search.

You should use "str_replace()" function for this
echo str_replace("dude=","","dude=99999");
Here first parameter your fix string which would be start as above , second parameter is replacement string, which is put as empty , third parameter is your actual string

If you're going to check all lines for different strings you can do as I have done recently:
// loop through all uploaded files:
for ($key = 0; $key < count($_FILES['file']['tmp_name']); $key++) {
// make an array of lines from a single file:
$txt_file = file($_FILES['file']['tmp_name'][$key]);
// loop through this array, line by line:
foreach ($txt_file as $line) {
// if your file is not utf-8 fix the encoding:
$line = iconv("windows-1251", "utf-8", $line);
// check if this string begins with 'Dude=':
if (substr($line, 0, strlen('Dude=')) === 'Dude=') {
// if yes, then trim the 'Dude=' and get what's after it:
$found_value[$key]['dude'] = trim(substr($line, strlen('Dude=')));
// if this string begins with 'Dude=' it cannot begin with something else,
// so we can go straight to the next cycle of the foreach loop:
continue;
// check if this string begins with 'Something else=':
} elseif (substr($line, 0, strlen('SomethingElse=')) === 'SomethingElse=') {
// if yes, then trim the 'SomethingElse=' and get what's after if:
$found_value[$key]['something_else'] = trim(substr($line, strlen('SomethingElse=')));
// if there's more items to find in the string use 'continue' to shorten server's work
continue;
}
}
}
I've adapted and commented it for you. Also you probably want to check if file(s) was uploaded properly, so you can use file_exists and is_uploaded_file
In the end you will get an array with structure like this:
$found_value [
1 => array()[
'dude' => 9999999
'something_else' => 'hello'
]
2 => array()[
'dude' => 3765234
'something_else' => 'hello again'
]
]

Related

Warning: stripos() expects at least 2 parameters in php

I wrote a simple function in php and passing arguments to uppercase the letters based on passing array index value but I'm getting this error
Warning: stripos() expects at least 2 parameters
what I'm doing wrong can anyone suggest me.
i'm newbie to php just starts learning.
<?php
function doCapital($string, $array)
{
$stringArray = explode(",", $string);
for( $i=0; $i<count($stringArray); $i++)
{
if(stripos($stringArray)>-1){
$stringArray[$i] = $stringArray[$i].ucfirst();
echo $stringArray[$i];
}
}
return implode(" ",$stringArray);
}
echo doCapital('abcd', [1,2]);
Apologies, on re-reading my last answer I realise that it did seem very unfriendly - I bashed out a quick answer and didn't read it back. What I was trying to say is that with errors like this the quickest solutions to go to the php manual and check the required parameters - which in this case is a needle and a haystack (i.e something to search, and something to search in).
You will likely find the same error here
$stringArray[$i] = $stringArray[$i].ucfirst(); as ucfirst requires a string to be passed - here you're using it like jQuery so php thinks you are trying to concatenate a string, it should say ucfirst($stringArray[$i])
you also can't explode with a comma unless your string contains them, so in the example you have you would receive the same string back, I think you mean to use something like str_split
also I would reiterate that I think you need to use in_array for what you're trying to achieve, like this:
function doCapital($string, $array)
{
$stringArray = str_split($string);
foreach($stringArray as $key => $value)
{
//see if the key exists in the array of characters to change the case for
//and update if it does
if(in_array($key,$array)){
$stringArray[$key] = ucfirst($value);//thinking about it I might just use strtoupper since there's only one letter anyway - I'm not sure that there's any real performance benefit either way
}
}
return implode("",$stringArray);
}
echo doCapital('abcd', [1,2]); //outputs aBCd
stripos - Find the position of the first occurrence of a case-insensitive substring in a string
You are missing the second parameter, The correct syntax to use the function stripos is
stripos ($haystack ,$needle);
Here
$haystack -> The string in which you are searching
$needle -> The substring
For example :
$findme = 'x';
$mystring1 = 'xyz';
$pos1 = stripos($mystring1, $findme);
if ($pos1 !== false) {
echo "We found '$findme' in '$mystring1' at position $pos1";
}

Problems with Empty Strings. Empty() not working

I'm building a form that'll create a Word doc. There's a part where the user will create a list, and will separete the list lines by using the " | " (vertical bar) as a delimeter. I'm trying to explode() a string like this: "First line| Second line| Third and last line |". As you guys saw, I placed a vertival bar delimiter after the last line, that's 'cause the user will probably do this mistake, and it will generate a empty line on the list.
I'm trying to avoid this error by using something like this:
$lines = explode("|",$lines);
for($a=0;$a<count($lines);$a++)
{
if(!empty($lines[$a]) or !ctype_space($lines[$a]))
{
//generate the line inside de Word Doc
}
}
This code works when I create the string by my own while testing the code, but won't work when the string come from a Form. And keep generating a empty line list inside the Word Doc.
When I var_dump() the $lines array it shows the last key as: [2]=> string(0) ""
I'm using Laravel and the form was created with the Form:: facade.(don't know if this matter, prob not)
If you guys could help me, I'd apreciate.
Alternatively just use array_filter with the callback of trim to remove elements that are empty or contain spaces before you iterate.
<?php
$string = '|foo|bar|baz|bat|';
$split = explode('|', $string);
$split = array_filter($split, 'trim');
var_export($split);
Output:
array (
1 => 'foo',
2 => 'bar',
3 => 'baz',
4 => 'bat',
)
However you might not want to remove some empty values!
You could just trim off your pipes to begin with:
<?php
$string = '|foo|bar|baz|bat|';
$string = trim($string, '|');
$split = explode('|', $string);
var_export($split);
Output as above.
Or use rtrim.
You may want to use PHP's && (and) rather than or.
For reference, see Logical Operators.
You only want to output the line if both empty() and ctype_space() return false. With your current code, blank strings will pass your if test because ctype_space() returns false even though empty() does not. Strings made up entirely of spaces will also pass because empty() returns false even though ctype_space() does not.
To correct the logic:
if(!empty($lines[$a]) && !ctype_space($lines[$a])) { ... }
Alternatively, I'd suggest trimming white space from the string before checking empty():
$lines = explode("|",$lines);
if (!empty($lines)) {
foreach ($lines as $line) {
if (!empty(trim($line)) {
// output this line
}
}
}
Also, see 'AND' vs '&&' as operator.

very large php string magically turns into array

I am getting an "Array to string conversion error on PHP";
I am using the "variable" (that should be a string) as the third parameter to str_replace. So in summary (very simplified version of whats going on):
$str = "very long string";
str_replace("tag", $some_other_array, $str);
$str is throwing the error, and I have been trying to fix it all day, the thing I have tried is:
if(is_array($str)) die("its somehow an array");
serialize($str); //inserted this before str_replace call.
I have spent all day on it, and no its not something stupid like variables around the wrong way - it is something bizarre. I have even dumped it to a file and its a string.
My hypothesis:
The string is too long and php can't deal with it, turns into an array.
The $str value in this case is nested and called recursively, the general flow could be explained like this:
--code
//pass by reference
function the_function ($something, &$OFFENDING_VAR, $something_else) {
while(preg_match($something, $OFFENDING_VAR)) {
$OFFENDING_VAR = str_replace($x, y, $OFFENDING_VAR); // this is the error
}
}
So it may be something strange due to str_replace, but that would mean that at some point str_replace would have to return an array.
Please help me work this out, its very confusing and I have wasted a day on it.
---- ORIGINAL FUNCTION CODE -----
//This function gets called with multiple different "Target Variables" Target is the subject
//line, from and body of the email filled with << tags >> so the str_replace function knows
//where to replace them
function perform_replacements($replacements, &$target, $clean = TRUE,
$start_tag = '<<', $end_tag = '>>', $max_substitutions = 5) {
# Construct separate tag and replacement value arrays for use in the substitution loop.
$tags = array();
$replacement_values = array();
foreach ($replacements as $tag_text => $replacement_value) {
$tags[] = $start_tag . $tag_text . $end_tag;
$replacement_values[] = $replacement_value;
}
# TODO: this badly needs refactoring
# TODO: auto upgrade <<foo>> to <<foo_html>> if foo_html exists and acting on html template
# Construct a regular expression for use in scanning for tags.
$tag_match = '/' . preg_quote($start_tag) . '\w+' . preg_quote($end_tag) . '/';
# Perform the substitution until all valid tags are replaced, or the maximum substitutions
# limit is reached.
$substitution_count = 0;
while (preg_match ($tag_match, $target) && ($substitution_count++ < $max_substitutions)) {
$target = serialize($target);
$temp = str_replace($tags,
$replacement_values,
$target); //This is the line that is failing.
unset($target);
$target = $temp;
}
if ($clean) {
# Clean up any unused search values.
$target = preg_replace($tag_match, '', $target);
}
}
How do you know $str is the problem and not $some_other_array?
From the manual:
If search and replace are arrays, then str_replace() takes a value
from each array and uses them to search and replace on subject. If
replace has fewer values than search, then an empty string is used for
the rest of replacement values. If search is an array and replace is a
string, then this replacement string is used for every value of
search. The converse would not make sense, though.
The second parameter can only be an array if the first one is as well.

How to get a line in a Text file using cakephp

So I know how to open a file in php is done using
fopen("file.txt", 'r') ;
but i want to get one line in the file and so some string manipulation on it.
such as " Serving this with <0101010> "
I want to find the line that starts with "Serving this" and take the whole line add it to $line
Then i will get remove the <> and add it to $number , and same for <0101010>
names of methods that can be used would be just perfect
Okay, the simple method you probably want to use is:
foreach (file("file.txt") as $line) {
if (strpos($line, "Serving this with") === 0) {
print "found";
The file function is easier than fopen/fread, as it returns a list of lines already. And the strpos function simply searches the string and returns the position. It must be checked with === 0 here, because it could also return false.
Instead of printing "found" you want to extract something, so you must again use strpos to find your delimeters < and > and then extract the part with substr:
$l = strpos($line, "<"); // well, actually needs more logic,
$r = strpos($line, ">"); // some if tests, if both are true
$wanthave = substr($line, $l, $r - $l + 1);
A simpler option I would use are regular expressions. And the regex itself looks simple enough in your case:
preg_match_all('/^Serving this with <(\d+)>/m',
file_get_contens("file.txt"),
$matches);
print_r($matches[1]);
you can also use fgets() read file line by line.
$line = fgets($file_handle);

Replace words - Ignore words between brackets

I'm using an ubb parser to convert several codes within brackets to html codes. I want to use a string replacer aswell to replace some unwanted words.
Now, I'm using this:
foreach($f AS $value) {
$escapeNamesArray[] = '/'.$value['woord'].'/i';
$escapeNamesReplace[] = '<span style="color: gray;">'.$value['vervanging'].'</span>';
}
$string = preg_replace($escapeNamesArray, $escapeNamesReplace, $string);
When I want to replace the word "Hello" to "Hey", everything is working fine. But when I place the word "Hello" between brackets, for example:
[url=http://www.hello.com]kdskdsds[/url]
The word "Hello" is replaced aswell. How can I change the pattern of the preg_replace function to ignore words between brackets?
Thanks for your reply!
Using preg_replace in HTMl-ish situations often turns into a mud pit. I highly recommend you find a different solution to this problem.
I'd suggest letting the parser do its work first, turning everything into valid XHTML. Then use something like SimpleXMLElement or DOMDocument to parse the document. You can then traverse the object, replacing bad strings in each element. When you're done, convert it back to an XHTML string.
This solution is a little more involved, but it's more robust and more flexible, especially if you decide to add more filters and replacements later.
Lucas is right, but its just a simple change to your existing code:
You just need to add make sure its ONLY matching words directly in-between [ ]
I have just added [ and ] in your pattern array (you need to escape them as they are normally used for a regex character array). Here is the updated code:
foreach($f AS $value)
{
$escapeNamesArray[] = '/ '.$value['woord'].' /i';
$escapeNamesReplace[] = '<span style="color: gray;">'.$value['vervanging'].'</span>';
}
$string = preg_replace($escapeNamesArray, $escapeNamesReplace, $string);
This is the only actually changed line:
$escapeNamesArray[] = '/ '.$value['woord'].' /i';
This will work with [whatever] [ whatever] [whatever ] but not [ whatever ]
I havent had a chance to test this, but it should work.
EDIT: Change the code slightly, please take another look :o)
You can make use of the BBCode PECL extension to do the heavy lifting for you. Check this out:
<?php
function filterWords($content, $argument) {
$badWordList = array(
'complex',
'regular expressions',
'O(n^2)'
);
return str_ireplace($badWordList, '', $content);
}
$bbcodeParserConfig = array(
'' => array(
'type' => BBCODE_TYPE_ROOT,
'content_handling' => 'filterWords'
),
'url' => array(
'type' => BBCODE_TYPE_OPTARG,
'open_tag' => '<a href="{PARAM}">',
'close_tag' => '</a>',
'default_arg' => '{CONTENT}',
'childs' => ''
)
);
$bbcodeParser = bbcode_create($bbcodeParserConfig);
$content = 'This is a complex url that [url=http://www.example.com]tells you nothing about regular expressions or O(n^2) algorithms[/url] and thankfully so!';
var_dump(bbcode_parse($bbcodeParser, $content));
There is also a BBCode parser written in PHP.
I would recommend taking each variable and splitting at the open and close bracket.
If it split at the open bracket then you know it contains an opening bracket. Call the replace on the string to the left of the open bracket (call var1). Then call split on the closing bracket and you know that the string to the left is the contents of the bracket so concatenate it to var 1 (called var2). Then call replace to the string to the right of the last split since it must have been outside of the closing bracket and concatenate the result to var2.
Example:
$exampleStr = "[url=http://www.hello.com]kdskdsds[/url]";
$piecesOfString = explode("[", $exampleStr);
// $piecesOfString[0] = "" --> before the opening bracket so if there was anything there you would have to replace
// $piecesOfString[1] = "url=http://www.hello.com]kdskdsds"
// $piecesOfString[2] = "/url]";"
$piecesOfStringSecond = explode("]", $piecesOfString[1]);
// $piecesOfStringSecond[0] = "url=http://www.hello.com" within the brackets so don't replace
// $piecesOfStringSecond[1] = "kdskdsds" //outside bracket so replace
$piecesOfStringSecond = explode("]", $piecesOfString[2]);
// $piecesOfStringSecond[0] = "/url" within the brackets so don't replace
// $piecesOfStringSecond[1] = "" //outside bracket so if length > 0 replace
I haven't checked this and I'm giving you this in pseudocode but:
$exampleStr = "begin[url=http://www.hello.com]kdskdsds[/url]between[url=http://www.second.com]dsfafa[/url]between2[url=http://www.third.com]kjhjkhk[/url]end";
$piecesOfStringOpen = explode("[", $exampleStr); //splits the string at the "["
for integer j = 0 to length of $piecesOfStringOpen {
if (j == 0) { // you know it will be the first part "begin"
// call replace on $piecesOfStringOpen[j] because you know it is outside of brackets
} else {
//this will include:
// $piecesOfStringOpen[1] = "url=http://www.hello.com]kdskdsds"
// $piecesOfStringOpen[2] = "/url]between"
// $piecesOfStringOpen[3] = "url=http://www.second.com]dsfafa"
// etc
$piecesOfStringClose = explode("]", $exampleStr); //splits the string at the "]"
for integer k = 0 to length of $piecesOfStringClose {
//if k == 0 then it was inside bracket, is a url and don't replace
//elsif k == 1 then it was outside bracket and you want to replace
}
}
}

Categories