php function problem - php

OK, one more problem and then I think my function will work.
Right now, my second function is just reporting the character length back next to the string like so:
string(20) "testing testing nice"
is there anyway to change the format of that return? And what do I need to change to get the WORD count too?
Is it even possible to make the format look like this:
string word count: 3 character count: 20 "testing testing nice"
thanks
file1.php
<?php
require('myfunctions.php');
if($_POST) {
$result = phptest($_POST['input']);
if ($result === false) {
echo 'No mean words were found.';
} else {
var_dump($result);
}
}
?>
<?php
echo "<br/> Sum function: ".sum(1,2,3,4)."<br/>";
echo "Average function: ".average(1,2,3,4)."<br/>";
?>
<form action="" method="post">
<input name="input" type="text" size="20" maxlength="20" />
<input name="submit" type="submit" value="submit" />
</form>
myfunctions.php
<?php
function sum() {
return array_sum(func_get_args());
}
function average() {
$args = func_num_args();
if ($args == 0) {
return 0;
}
return array_sum(func_get_args()) / $args;
}
?>
<?php
function phptest($input) {
$search = array('ugly', 'rude');
$replace = array('nice', 'sweet');
$output = str_ireplace($search, $replace, $input, $replace_count);
if ($replace_count === 0) {
return false;
} else {
return $output;
}
}
?>

You can use the str_word_count function to count words in a string.
function str_info($string) {
$words = str_word_count($string);
$chars = strlen($string); //Consideer using mb_strlen if you're using Unicode
return 'string word count: '. $words .' character count: '. $chars .' '. $string;
}

Related

Replace squared brackets with div tags

Can someone please help me with this:
For example I have this string:
"
[row]
[col-md-6 col-lg-3]
Lorem ipsum sit dolor amet... And the rest of the text
[/col]
[/row]
"
Is there any way in PHP to replace this squared brackets with
<div class="<some_dynamic_tags>">
Here's some of my code. It only works for closing tags ( [/col], [/row]). Still don't know how to solve this problem for opening tags.
class Html extends BaseHtml
{
public static function containsChar($haystack, $needle)
{
$pos = strpos($haystack, $needle);
if ($pos === false)
{
return false;
}
else
{
return true;
}
}
public static function doShortcode($string)
{
if (Html::containsChar($string, '/'))
{
// This is a closing tag
return '</div>';
}
else
{
// This is an opening tag
}
}
public static function bootstrapShortcode($text)
{
preg_match_all("/\[([^\]]*)\]/", $text, $matches);
$htmlText = $matches[1];
echo nl2br($text) . '<br>';
foreach ($htmlText as $val) {
var_dump(Html::doShortcode($val));
}
return $htmlText;
}
}
There are two ways to do that
<?php
echo "<div class='yourClass'>'{$yourVariable}'</div>";
?>
or
<?php
echo '<div class="yourClass">"{$yourVariable}"</div>';
?>
Depends what you need.
You're probably looking for something along the lines of
return '<div class="'.substr($string, 1, strlen($string) - 2).'">';
When $string is "[col-md-6]", <div class="col-md-6"> is returned.

Extract particular values from string as distinct variables

I'm trying to extract and assign values of CEO, Chairman and any other key positions to distinct variables. I was wondering how this can be done and what the best method to use is. Please see my code below which has a variable $keypeople but I'd like this to be further broken down into variables $CEO; $Chairman etc. depending on the roles contained in $keypeople. In the example below the $keypeople variable returns the following string:
key_people = {{unbulleted list|[[Larry Page]] ([[CEO]])|[[Eric Schmidt]] ([[Chairman]])|[[Sergey Brin]] (Director of [[Google X]] and Special Projects){{cite web|url=https://www.google.co.uk/intl/en/about/company/facts/management/ |title=Management Team - Company - Google}}}}
Any assistance in much appreciated.
<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$search = ucwords($search);
$search = str_replace(' ', '_', $search);
$url_2 = "http://en.wikipedia.org/w/api.php?
action=query&prop=revisions&rvprop=content&format=
json&titles=$search&rvsection=0&continue=";
$res_2 = file_get_contents($url_2);
$data_2 = json_decode($res_2);
?>
<h2>Search results for '<?php echo $search; ?>'</h2>
<?php foreach ($data_2->query->pages as $r):
?>
<?php foreach($r->revisions[0] as $a);
if (preg_match_all('/key_people += (.*)/', $a, $result)) {
$keypeople = trim($result[0][0]);
echo $keypeople;
} else {
echo 'Not found';
}
?>
<?php endforeach;
?>
<?php
}
?>
</body>
</html>
$people = array();
$split = explode('|', $keypeople);
foreach ($split as $str) {
if (preg_match('/\[\[([^]]+)\]\] \(([^)]+)\)/', $str, $match)) {
$people[str_replace(array('[[', ']]'), '', $match[2])] = $match[1];
}
}
var_dump($people);
The regexp matches anything with the pattern [[name]] (role).
Output:
array(3) {
["CEO"]=>
string(10) "Larry Page"
["Chairman"]=>
string(12) "Eric Schmidt"
["Director of Google X and Special Projects"]=>
string(11) "Sergey Brin"
}

Max function not returning correct result

I am trying to get the maximum value from an array using max finction in php. However despite making sure that the array appears as I expect using print_r, the max($array) returns the wrong result.
Please see the code below, I used "simple_html_dom.php" from http://simplehtmldom.sourceforge.net/. I am expecting a value of 220, but when I echo max($items) it returns 24 when submit is clicked. Any assistance is much appreciated.
<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="google"/>
<input type="submit" value="Submit">
</form>
<?php
include 'simple_html_dom.php';
if (isset($_POST['q'])) {
$search = $_POST['q'];
$search = ucwords($search);
$search = str_replace(' ', '_', $search);
$html = file_get_html("http://en.wikipedia.org/wiki/$search");
?>
<h2>Search results for '<?php echo $search; ?>'</h2>
<ol>
<?php
$items = array();
foreach ($html->find('img') as $element): ?>
<?php $photo = $element->src;
$logo = 'Logo';
if(strpos($photo, $logo))
{
if (preg_match_all('/[0-9]+px/', $photo, $result)) {
echo '<br/>';
$rp = trim($result[0][0],"px") .'<br/>';
$items[] = $rp;
} else {
echo "Not found";
}
}
?>
<?php endforeach; echo max($items);
print_r($items);?>
</ol>
<?php
}
?>
</body>
</html>
Here is result of var_dump($items):
array (size=2)
0 => string '220<br/>' (length=8)
1 => string '24<br/>' (length=7)
As you see, it takes it as a string. So max() works as it should, and you need to properly format it first, cut tags and cast to int.
Assuming it's an integer, simply change $items[] = $rp; to $items[] = intval($rp);... As an example this will change the array entry from '220<br/>' (string) to 220 (integer).

Nested conditional using radio buttons to guide script in PHP

I've been working on this for a while and I can't seem to figure it out. I know it must be something really simple. Basically I have a script that works as a program that translates English to Piglatin, and it works fine, but I want the user to have a choice of whether or not to actually operate that script, by using a radio form with the text input that says "English" or "Piglatin". I've tried all different ways to get this to work, but using a nested conditional seems like it would be the most logical answer to me. However, whenever I try to run the script with it, it doesn't work. Can someone please tell me what I'm doing wrong?! It would be much appreciated. Thanks!
HTML Form:
<p><input type="text" name="original" size="20" maxlength="40" /></label></p>
<p><input type="radio" name="english" value="yes"/>english <input type="radio" name="english" value="no"/>piglatin</p>
<input type="submit" name="submit" value="submit" /></form>
PHP:
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
}
elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
}
else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
else
{echo $original.".";
};
?>
Like I said, I'm sure it's something really small and simple that I just can't see because I've been looking at the code so long. Any help is appreciated! Thank you!
Sort your indentation out and you will see your missing closing brackets.
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
} elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
} else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
} else {
echo $original.".";
};

Search instead filename

I have this script to search file into a directory.
Works well when i perform search with exactly term, example: "my file.doc", "sales order 1234.pdf"
Can anyone help me to modify to search word into filename, example: "file" ou "Sales"
TKS
Cris.
<?php
if($_POST['search']) {
$word = $_POST['file'];
$dir = './';
$list = new RecursiveDirectoryIterator($dir);
$recursive = new RecursiveIteratorIterator($list);
$num = 0; //
foreach($recursive as $obj){
//echo $obj->getFilename().'<br />';
if($obj->getFilename()=="$word"){
echo $obj->getPathname().'<br/>';
$num++;
}
}
echo "found(s) $num file(s).";
}
?>
<form action="" method="POST">
search files. <input type="text" name="file" value="">
<input type="submit" name="search">
</form>
<?php
if($_POST['search']) {
$word = $_POST['file'];
$dir = './';
$list = new RecursiveDirectoryIterator($dir);
$recursive = new RecursiveIteratorIterator($list);
$num = 0; //
foreach($recursive as $obj){
//echo $obj->getFilename().'<br />';
if( strpos( $obj->getFilename(), "$word" ) === true ){
echo $obj->getPathname().'<br/>';
$num++;
}
}
echo "found(s) $num file(s).";
}
?>
<form action="" method="POST">
search files. <input type="text" name="file" value="">
<input type="submit" name="search">
</form>
You can use the strpos function or the strstr function on your filename.
Test if the function returns something different than false to know your filename contains your chain.
You can use PHP's substr_count to count the occurrences of a string in another, but since you need one or more you can check like this:
if( substr_count( $obj->getFilename(), $word ) ){
echo $obj->getPathname().'<br/>';
$num++;
}
edit: for case-insensitive comparison:
if( substr_count( strtolower($obj->getFilename()), strtolower($word) ) {
// ...
}

Categories