Jump to content

Psycho

Moderators
  • Posts

    12,157
  • Joined

  • Last visited

  • Days Won

    129

Everything posted by Psycho

  1. If the value is a negative integer - it should fail. Factorials of negative numbers is not possible (e.g. division by zero) - unless you want to get into abstract complex numbers which would require the use of the gamma function. The only valid values for a factorial are positive integers from zero to ∞. The only exception I can think of to the ctype_digit() test would be if you wanted to allow a plus symbol; in which case you would still need to remove it during the computation.
  2. The OP never stated "where" the value is coming from. If the value is coming from a POST/GET variable it will ALWAYS be a string and always fail the is_int() test - even if the value is something like "5". If the value is specifically cast as an integer then there would be no reason to even test if it is an integer to begin with. So, it would only make sense to test if the value "looks" like an integer when it is an unknown string value that can be a string representation of an integer or some other invalid value. @Barand's test makes more sense.
  3. FWIW, what the task to specifically create a recursive function? If not, you can get a factorial much simpler (of course you'd still want the integer check array_product(range(1, $number));
  4. There is nothing in that code to sort the results in the array. readdir() (as stated in the manual) returns the results " . . . in the order in which they are stored by the filesystem". You could determine the file date and sort by that, but since you are copying them from one device to another, there is a good chance that the file date will be changed in that process. Sometimes the date changes in a copy process and sometimes it does not - depends on the process used. Also complicating things, filetime() will return different values based on the filesystem. As I understand it, in Windows it returns the creation time, whereas in Unix it returns the modification time. So, you could potentially sort using filetime() IF the original file creation times are preserved after they are copied AND filetime() returns the creation date. You should be able to verify if those are both true in your case. If so, get the creation date using filetime() and sort on that. If that is NOT the case, then you could either ensure they are copied in the correct order (i.e. one at a time in the order they were created) or you need to sort using some manner. For example, the named of the files is sequential. So you could sort by file name. But, when you go from IMG_9999.jpg to IMG_10000.jpg it will break that logic as IMG_1... comes before IMG_9... when sorting alpha-numerically. Of course, you could always parse the file names and convert them to have x number of digits, i.e. IMG_9999.jpg converts to IMG_0009999.jpg and IMG_10000.jpg converts to IMG_0010000.jpg. Also, your phone *may* restart that numbering at some point which basically screws all of that up. So, lots of possibilities, but no bullet-proof solution. The *best* solution would be predicated on the questions on how the files are handled in the environment (dates when copied, whether file names change, etc.).
  5. The PHP code you present puts single quotes around the parameter values, but you are stating that the code in the browser has double quotes around the parameter values. If that is the case, then something is changing the content. What you showed as the output for the $ename variable also points to this. I've known browsers to "self correct" bad code with respect to the display (e.g. if closing tags are missing they may assume they are there), but I've never known a browser to change the code (if that is what is doing it). That is going to make debugging much more difficult than it should be,
  6. What he said. There is no way to positively determine if an element is a folder or file by the name. A files doesn't have to have an extension. It's kind of difficult to create a file w/o an extentiosn, but not impossible. But, the function is_dir() [or the converse is_file()] will positively make that distinction.
  7. @Adamhumbug What you have posted is impossible and, if the problem is even remotely as you say it is, has nothing to do with a ' character. You show that you are outputting the content using [ic]echo "<td><a class='btn btn-primary col-sm-12' . . . [/ic] Where the string is defined using double-quotes and the parameters of the tags are in single quotes. But, then you show that output like this: [ic]<a class="btn btn-primary col-sm-12" . . . [/ic] Where the parameters are in double quotes. That is not possible. And it would make HUGE difference in the output based on if the variables have single/double quotes Secondly, you state that the value causing the problem is due to a ' character. That is also not possible. If this [ic]data-active-sheets='".$ename."'>Manage</a></td>";[/ic] Produces this: [ic]data-active-sheets="A new event,Chelsea" s="" event'="">Manage</a>[/ic] Then the value of $ename is A new event,Chelsea" s="" event'=
  8. Not sure why you have all the unnecessary parameters in the function - unless there is some use I am not seeing. This will produce the same output function groupAndExtractByAspect($inputAry, $aspect) { $outputAry = array(); foreach($inputAry as $key => $dataAry) { //Skip if not the selected aspect if($dataAry['aspect'] != $aspect) { continue; } $outputAry[$dataAry['density']] = $dataAry['resolution']; } return $outputAry; } $showArray = groupAndExtractByAspect($arrayVideoSpecs, '16:9'); echo '<pre>'; print_r($showArray); echo '</pre>'; Alternatively, you could just generate a new multi-dimensional array that create the values for ALL aspect ratios function groupAndExtractByAspect($inputAry, $aspect) { $outputAry = array(); foreach($inputAry as $key => $dataAry) { $outputAry[$dataAry['aspect']][$dataAry['density']] = $dataAry['resolution']; } return $outputAry; } This will produce: Array ( [4:3] => Array ( [442368] => 768x576 [307200] => 640x480 ) [16:9] => Array ( [2073600] => 1920x1080 [121600] => 1280x720 ) )
  9. As @gw1500se stated, the DELETE query is malformed as it does not include the "FROM" parameter, but it still won't work with that $conn->query("DELETE email_user WHERE id='$user_id'"); $user_id is never defined!!! Aside from that, there are quite a few problems and poor construction. Here are some tips: 1. Put your DB connection logic in a separate file and include() it on the pages you need it. If you need identical code on multiple scripts, don't use copy/past coding. If you ever need to make a change in your DB connection you would only have to change it one place and not many. 2. Never user "SELECT *". There are performance and security problems with doing that. Always list the fields you want. 3. Don't suppress errors using the '@' symbol. You could have simply used an isset() check for the variable in your script. if(isset($_GET['key']) && $_GET['key']!=""): 4. I would highly suggest not wrapping your error conditions in nested if/else conditions in this manner as it makes it difficult to easily "see" which results go with which error if(!error_condition_1) { if(!error_condition_2) { if(!error_condition_3) { //Success result } else { //error result 3 } //error result 2 } //error result 1 } This is MUCH more readable and maintainable IMO if(error_condition_1) { //error result 1 } elseif(error_condition_2) { //error result 2 } elseif(error_condition_3) { //error result 3 } else { //Success result } 5. You are switching back and forth between object oriented and procedural. Stick with one for consistency $fetch = $conn->query("SELECT * FROM email_user WHERE hash = '$hash'"); //$count = mysqli_num_rows($fetch); $count = $fetch->num_rows; 6. Use prepared statements for your queries. 7. No need to use a SELECT statement before running the DELETE query. A race condition can create problematic results. You can just run the DELETE query and then check the number of affected rows. If 0, then there was no matching record, else if 1 then you can tell the user they were unsubscribed.
  10. First, use glob() to store the results into an array variable. Then you can perform operations on that array BEFORE you use the foreach() loop to generate the output. E.g. //Get the files in the directory $filesAry = glob("{$directory}/*"); //Sort the array in reverse order rsort($filesAry ); //Output the results foreach($filesAry as $file) { //Create the output } If you want to sort by date/size/etc, then where I have rsort() above, I would run a foreach() loop over the file names and create a multi-dimensional array with all the data, then you can use usort() with a custom function to sort however you wish.
  11. You're saying this produced no results? $globFiles = glob('*'); echo "<pre>" . print_r($globFiles, 1) . "</pre>"; I find that hard to believe. If you were only trying the code from the manual then, yes, I could see that not producing any results because you many not have ant "txt" files in the directory being scanned. Yes it does. And '*' is a reference because the path can be relative from the current working directory. Using '*' should return all the files in the current working directory (i.e. the directory in which the script is executed from). That is why I find it hard to believe that the test code I asked you to try earlier is producing no results. Just to be sure I did not make a mistake, I just ran that code again and it returned all the contents of the directory where I ran the script as expected. Is it returning an empty array or an error? Try this test script and paste the results here: $pattern = '*'; $globFiles = glob($pattern); if($globFiles===false) { echo "glob('{$pattern}') returned an error"; } else { echo "Results of glob('{$pattern}'): <pre>" . print_r($globFiles, 1) . "</pre>"; }
  12. No you don't want to take the time to actually learn anything and just want us to provide solutions. If you had simply done a quick test using glob() I'm confident you would have already had a solution and moved on. Instead, we've wasted quite bit of time in this thread and you are probably further from a solution because you are getting lost in assumptions and trial & error attempts. That must be really frustrating for you. I've already resigned myself that I am not going to give you the solution. You have to earn it. You were right that the part you need to change was within those four lines you posted earlier. But, you can't just replace using the glob() function and expected it to work. If you had just a basic understanding of what those four lines do and what glob() does it is a very simple solution. This will be my final attempt to help you unless you can demonstrate that you are at least putting in some (worthwhile) effort. Here is what you have $directoryList = opendir($directory); while($file = readdir($directoryList)) { if ($file != '.' && $file != '..') { $path = $directory . '/' . $file; If you were to put comments in your code you may have figured it out already. Since you didn't let's review what that code does: 1. The first line creates a "handle" to the directory (think of it like making a connection to a database). So, the variable $directoryList is misnamed because it isn't a list. 2. Here you have a while list that will continue as long as a new record can be assigned to $file from the readdir() function. That function returns each record name found in the file handler created above 3. The if() statement ensures that the default filesystem objects of the current and parent directories are not included in the processing 4. This defines (I assume) the fill path to the file. So, what does glob() do? It returns an array of files based on an expression. So, obviously your looping logic needs to change since you wouldn't use a while() loop to iterate over an array. Typically you want a foreach() loop, correct? A foreach() loop will return the value of each element in the array. But, how do you get the correct values in the array? Well, you could just throw random data into the glob() function and scratch your head when things don't work. Or, you could take the two line test script I provided and modify the pattern to verify you are getting the right values before you try using it in a foreach() loop of your current logic. FYI: glob() does not return '.' and '..', so the if() condition will be unnecessary. Good luck
  13. So, you didn't follow my advise to start with a simple test script to see what glob() is returning and then go from there? Instead, you're back still trying to shoehorn it into your current code without understanding what it is doing. It seems you don't even understand what your current code is doing. You need to stop the trial and error approach to coding and actually learn what the functions do. You're being lazy in a way that is causing you more work.
  14. Yeah, that's a mystery isn't it. It's not like it is explained in the manual on the first sentence of the description for the readdir() function, right? Nope, you have to read all the way to the second sentence . You probably created those first three files such that they happened to be created in alphabetical order. The fact that it is right there plain as day in the manual for that function would lead someone to believe you never took the time to do even a cursory look at the manual. I had no idea of how readdir() determined the order in which it returned files, and it took me all of 5 seconds to find out without any special skills/knowledge required to do so. It leaves one wondering what level of effort was put into understanding the glob() function before just randomly trying things without even understanding what the problem is "I have tried renaming the $path, and nesting the glob() in every area of my script." Did you have a reason to believe the path was wrong or that glob() should go somewhere else in the script? When using a function for the first time, if I have any problems I will almost always create a test script. I will start with an example from the manual or a tutorial, verify it works and then figure out how it needs to be modified for my use. I have a very good idea of what your problem is, but I'm reticent to give you the solution because you are wasting our time and yours with how you are currently approaching the problem. And, I'm certain you will be back time and again with 'simple' problems that end up taking significant time to resolve. You need to learn how to problem solve. Start with this code and see what the results are. Then start making (small) changes until it is returning the results you want. E.g. I'd start by changing it to get to the intended directory. Then I would change it to only return the files I was interested in. If you want further help from me, please provide details on what you tried up till you got stuck. $globFiles = glob('*'); echo "<pre>" . print_r($globFiles, 1) . "</pre>";
  15. Why would you think that? As previously stated in this thread: The manually explicitly states this as well. It doesn't state a path/directory name - it states a pattern. If you look at any of the examples either in the manual or the ones linked to by others, you would see that it takes more than just the path to the directory. Heck, @cyberRobot asked you to provide the value of the variable $directory so we could help, but you refused and are simply wanting us to do it for you. readdir() is designed to return all the contents of a directory - so it only needs a pointer to the directory. glob() is designed to return a filtered list of a directory's contents and therefore needs something more than just the path to the directory. Regular expressions (i.e. the pattern) is one of the more difficult areas of programming (IMO), so it would be understandable if you were to ask about how to write the expression. But, instead you just put what you "think" it should be and don't respond to direct questions. I think you are taking the responses as people not being helpful. What I see are people that are trying to get you to think deliberately and analytically in order to find answers for yourself. Or to at least get a sense of the problem so you can ask the right questions. I for one am more likely to help someone who can demonstrate through their questions/responses that they've done some research into their problem rather than just throwing code at the wall to see what will stick. Having said all that (which will probably be forgotten by the next post), I will throw you a bone. The '*' character is a 'character class' that matches anything. The link @cyberRobot posted had this example: $files = glob("/path/to/directory/*.txt"); Which will " . . . find all the files in the directory /path/to/directory with a .txt file extension" because the '*' would match any number of characters after the path name and before the '.txt'. So, what would happen if you removed the '.txt' from that pattern? It would match anything that comes after the directory path (i.e. any files/folders). However, since you are looking for images, why not use the later example on that page which was specifically built to only return images?
  16. Even session data can be "hacked". Everything can be "hacked" it is just a matter of how difficult it is. The amount of effort and safeguards you put in place should be directly proportional to the "value" or "risk" associated with the data being secured. Unless you are dealing with financial or sensitive PII data, I think using a session value as @mac_gyver stated is perfectly acceptable. Although you should at least read the manual regarding sessions to take the basic precautions.
  17. None of what you described requires the code to be in the same page or not. For small projects, it's fine. But, it is significantly easier to manage code when you have separate files based on separate purposes.
  18. Put the code in your post as text (using the code tags) not as an image. As to your problem. this is NOT doing what you think it is if($Name_Tag = 15) Read this: Comparison Operators
  19. On your gallery page, you have a process to get an array of images which you should ensure has a numerically based index (0, 1, 2, ...). First, you need to take that logic and put it in a separate file that you will include() in your gallery page. You need to do this because you will need to include the same logic on the "enlarged version" script so you always get the exact same array. Never "copy/paste" such logic between multiple pages - especially when those multiple pages are dependent upon the data being the same. Then, on your gallery page, make each image a link to open the image in the "enlarged version" page. That link would look something like this showfull.php?id=3 Lastly, your enlarged version page could look something like this. <?php //Include script to generate the image array include('getImageArray.php'); //Get the passed image id $imageId = isset($_GET['id']) ? int($_GET['id']) : 0; //Check if the image exists if(!array_key_exists($imageId, $images) { //Error handling when the selected image does not exist $output = "Unable to retireve image"; } else { //Detemine if there will be a "prev" button (assumed array is always zero-based $prevId = $imageId-1; $prevLink = (array_key_exists($prevId, $images) ? "<a href='showfull.php?id={$prevId}'>PREV</a>" : ''; //Detemine if there will be a "next" button $nextId = $imageId+1; $nextLink = (array_key_exists($nextId, $images) ? "<a href='showfull.php?id={$nextId}'>NEXT</a>" : ''; //Create the output $output = "SOME CONTENT TO SHOW FULL-SIZE IMAGE<img src='base_path/{$images[$imageId]}' /><br>"; $output .= "{$prevLink} | {$nextLink}"; }
  20. Have you inspected the HTML output to see if the text is there, but maybe is not within proper HTML tags making it 'hidden'? Your code is hard to follow for a number of reasons. But, my guess, is that there is a problem with the structure of the output. So, a couple of suggestions: 1. When checking for multiple error conditions, do not do this if(NOT error_condition_1) { if(NOT error_condition_2) { //Success handling } else { //Error condition 2 handling } } else { //Error condition 1 handling } Instead, structure it so the error condition handling is adjacent tot he error condition check. Plus, try not to have a lot of nested if/else conditions. It makes the code much more readable. if(error_condition_1) { //Error condition 1 handling } elseif (error_condition_2) { //Error condition 2 handling } else { //Success handling } 2. use prepared queries. NEVER use user submitted data directly in a query 3. You aren't checking to see that the user provided the top_text or that you are even getting the value. I.e. if the field name was different between the form and the processing page it would insert an empty string. I'm assuming the problem is here and the value you think is being passed isn't referenced correctly and not getting set in the DB <?php // Include the database configuration file include 'database/dbConfig.php'; $statusMsg = ''; // File upload path $targetDir = "uploads/"; $fileName = isset($_FILES["file"]["name"]) ? basename($_FILES["file"]["name"]) : false; $top_text = filter_input(INPUT_POST, 'top_text'); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); //Create Prepared statement $stmt = $pdo->prepare("INSERT into images (file_name, top_text, uploaded_on) VALUES (?, ?, NOW())"); // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf'); //Check if there was an upload if($fileName && $fileName!=''){ $statusMsg = 'Please select a file to upload.'; } //Verify top_text is valid elseif (!$top_text || $top_text=='') { $statusMsg = 'Please provide the text.'; } //Verify valid file type elseif(!in_array($fileType, $allowTypes)) { $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.'; } //Attempt to upload file elseif (!move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) { $statusMsg = "Sorry, there was an error uploading your file."; } //Attempt the insert query elseif(!$stmt->execute([$fileName, $top_text]);) { $statusMsg = "The file {$fileName} has been uploaded successfully."; } else { //Insert succeeded $statusMsg = "File upload failed, please try again."; } // Display status message echo $statusMsg; ?> 4. The 2nd block of code is hard to read because of the breaking in and out from PP/HTML repeatedly. Also, there is a TON of style properties in there. You should use a style sheet with classes. The complexity in the structure makes it impossible to see structure errors. After cleaning it up, I see that the closing LI tag for the default slide it outside the else container block for that slider. In other words, that closing LI tag is always outputting to the page - even when the default slider is not used. I don't see that this would cause your issue, but it just shows that such simple problems are hidden in that morass of code. There may be other errors that I can't "see" because of all the style properties, but here is a more readable re-write of that section <!-- Revolution slider --> <section id="slider"> <div class="tp-banner-container "> <div class="tp-banner rev-banner-fullscreen"> <ul> <!-- SLIDES --> <?php // Include the database configuration file include 'database/dbConfig.php'; // Get images from the database $query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC"); if($query->num_rows = 0) { ?> <!-- DEFAULT SLIDE --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="images/slide/slide-5-bg.jpg" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> New Arrival </div> </li> <!-- /END DEFAULT SLIDE --> <?php } else { while($row = $query->fetch_assoc()){ ?> <!-- DYNAMIC SLIDES --> <li data-index="rs-140" data-transition="slideup" data-slotamount="default" data-easein="default" data-easeout="default" data-masterspeed="default" data-thumb="" data-rotate="0" data-saveperformance="off" data-title="1/2" data-description=""> <!-- MAIN IMAGE --> <img src="uploads/<?php echo $row["file_name"]; ?>" alt="" style='background-color:#f4f4f4' alt="" width="482" height="800" data-bgposition="center center" data-bgfit="cover" data-bgrepeat="no-repeat" class="rev-slidebg" data-no-retina> <!-- LAYERS --> <!-- LAYERS 1.2 --> <div class="tp-caption tp-resizeme" id="slide-1-layer-2" data-x="['left','left','left','left']" data-hoffset="['102','102','67','40']" data-y="['top','top','top','top']" data-voffset="['150','150','60','60']" data-fontsize="['18','18','14','14']" data-width="['345','345','345','259']" data-height="none" data-whitespace="normal" data-transform_idle="o:1;" data-transform_in="y:50%;z:0;rX:0deg;rY:0;rZ:0;sX:1;sY:1;skX:0;skY:0;opacity:0;s:900;e:Power4.easeInOut;" data-transform_out="x:-50%;opacity:0;s:800;e:Power2.easeInOut;s:300;e:Power2.easeInOut;" data-start="500" data-splitin="none" data-splitout="none" data-responsive_offset="on" style="z-index: 6; min-width: 345px; max-width: 345px; white-space: normal; color: #3e3e3e; font-family: 'Montserrat'; letter-spacing: 7px;"> <?php echo $row['top_text']; ?> </div> </li> <!-- /END DYNAMIC SLIDE --> <?php } } ?> </ul> </div> <!-- /tp-banner --> </div> <!-- /tp-banner-container --> </section> <!-- /#Revolution slider -->
  21. To add to @maxxd's response. When a user requests a PHP page from a web server, the web server will first execute any php code in the page. The results after the php code is execute is then sent to the user/browser. If you are having problems in the page rendered in the browser, there is something off in the output (HTML, Javascript, etc.) sent to the browser. It can get confusing when you are using a programming language (PHP) to dynamically create other code (JavaScript) or Markup (HTML).
  22. It's pretty frustrating when someone asks for help and then they change the requirements. It would also be helpful if you provided REAL content instead of something with gibberish. <?php $text = "start 00000000000000000 REMOVE ON FIRST PASS end start 11111111111111111111 XXXXXXX keyword XXXXXXXXXXX end start oidfgoj 11111111111111111111 keyword REMOVE ON 2ND PASS end start abcd keyword efg 2222222222222222222 REMOVE ON 2ND PASS abcd keyword abcd end SOME OTHER TEXT WILL NOT BE REPLACED start 0000000000000000000 REMOVE ON FIRST PASS end start keyword oidfgoj 33333333333333333333333 abcd REMOVE ON 2ND PASS abcd keyword fdsfs keyword pwefkoewfk end"; function replaceTextBlocks($input, $startDelimiter, $endDelimite, $keyword='keyword', $withKeyword=false) { if($keyword!='') { $keyword = "{$keyword}.*?"; } //$pattern = "#^{$startDelimiter}.*?{$keyword}{$endDelimite}#ms"; if(!$withKeyword) { //Remove blocks w/o the keyword $pattern = "#^{$startDelimiter}((?!{$keyword}).)*{$endDelimite}[\n\r]*#ms"; } else { //Remove blocks with the keyword $pattern = "#^{$startDelimiter}.*?{$keyword}.*?{$endDelimite}[\n\r]*#ms"; } //echo $pattern; $newText = preg_replace($pattern, '', $input); return $newText; } echo "Original text: <pre>{$text}</pre><br>\n"; $text = replaceTextBlocks($text, 'start', 'end', 'keyword'); echo "First Pass: <pre>{$text}</pre><br>\n"; $text = replaceTextBlocks($text, 'start', 'end', 'keyword', true); echo "Second Pass: <pre>{$text}</pre><br>\n"; ?>
  23. Pleas explain what you expect that code to do and then describe what it is doing (or not doing) that is contrary to your expectations. Are there errors? FYI: there is nothing in that code that ever calls that function. So, kinda hard to say it isn't working, when it is not used.
  24. Do you understand WHY that last attempt worked and the previous ones failed? If not, you are going to repeat the same errors in the future.
  25. This may work for you. Here is a function that returns the "textblocks" that begin/end with a delimiter string OR (if a keyword is provided, then it only returns "textblocks" that also contain that keyword. As I made the regular expressions programatical, it may be difficult to see how they are constructed. The two formats would look like this: #^smaple.*?smaple#ms and #^smaple.*?keyword.*?smaple#ms <?php $text = "smaple woiefjeowijji oj oiewjfoewijfoiwejfiojewf keyword owiejfioejoij oiewjfioewjf smaple smaple ojioewj fijo oieiojewf keyword owiejfioejoij oiewjfioewjf smaple smaple woiefjeowijji fijo oiewjfoewijfoiwejf owiejfioejoij oiewjfioewjf smaple"; function findTextBlocks($input, $delimiter, $keyword='') { if($keyword!='') { $keyword = "{$keyword}.*?"; } $pattern = "#^{$delimiter}.*?{$keyword}{$delimiter}#ms"; echo $pattern; preg_match_all($pattern, $input, $matches); return $matches; } $textBlocks = findTextBlocks($text, 'smaple'); echo "<pre>".print_r($textBlocks, true)."</pre>"; $textBlocksWithKeyword = findTextBlocks($text, 'smaple', 'keyword'); echo "<pre>".print_r($textBlocksWithKeyword, true)."</pre>"; ?> Output #1 Output #2
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.