Extract particular values from string as distinct variables - php

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"
}

Related

how to validate "provide at least 2 tags, separated by commas" from tag textfield in php?

HTML
<h3>Tags</h3>
<input <?php echo $err_st3; ?> type="text" name="tags" id="textfield"
placeholder="Example: tag, another tag, hello tagging" value="
<?php echo #$tagsOK; ?>">
Php
$tags=array();
$tagline = $_POST['tags'];
//TAGS
if(!empty($tagline)){
$tokens = str_replace(' ', '', $tagline);
$tags = explode(',',$tokens);
$tags = array_unique($tags);
foreach ($tags as $tag) {
if(preg_match("/^[0-9a-zA-Z]$/",$tag) === 0) {
// error
}
else{
echo $count_tags = $count_tags+1;
}
}
if($count_tags <= 1){
$error[]=" - Please provide at least 2 tags, separated by commas.";
$err_st3 = $st;
}
$tagsOK = implode(', ',$tags);
}
else{
$error[]=" - Please provide at least 2 tags, separated by commas.";
$err_st3 = $st;
}
When I enter the letters like "a, b", then it will be valid.
But it does not validate words like "vehicle, characters, scene"
Instead of doing preg_match check length:
strlen($tag)==1

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).

How to combine strings inside foreach into single string PHP

I have code like this
$word = 'foo';
$char_buff = str_split($word);
foreach ($char_buff as $chars){
echo var_dump($chars);
}
The output was
string(1) "f"
string(1) "o"
string(1) "o"
For some reasons, I want to make the output become only 1 string like this:
string(3) "foo"
I tried with this
$char.=$chars;
echo var_dump($char);
But it shows error Undefined variable: char.
I'm going to assume that you have a good reason for splitting it up, only to put it back together again:
$word = 'foo';
$result = "";
$char_buff = str_split($word);
foreach ($char_buff as $char){
$result .= $char;
}
echo var_dump($result);
Which outputs the following:
string(3) "foo"
str_split() converts a string to an array. There's no need to use this function if you want to keep the whole word.
I would just use implode, much like this:
$string = implode('', $char_buff);
So, why do you split it just to make it a string again?
$word='foo'
$char_buff = str_split($word);
$final = array();
foreach ($char_buff as $chars){
$final[] = $chars;
}
var_dump( implode('', $final) );
Sounds like you are looking for implode()
http://php.net/manual/en/function.implode.php
As for the code you posted
$chars .= $char;
is probably what you were trying to do
Kind of strange to split a string, and then glue it together again, but here goes:
$word='foo'
$char_buff = str_split($word);
// this is what is missing, you have to define a variable first
$newword = "";
foreach ($char_buff as $chars){
$newword .= $chars;
}
echo var_dump($newword);
<?php
$word = 'foo';
$char_buff = str_split($word);
// here is the trick
$length = count($char_buff);
$char_buff[$length] = $word;
foreach ($char_buff as $chars)
{
echo var_dump($chars);
}
?>
Maybe some of you are looking for this answer.
I think var_dump() is no longer necessary for this problem.
<?php
if(isset($_POST['test'])){
$result = '';
for($x=1;$x<=4;$x++){
$ans = $_POST['ans'.$x];
$result .= $ans;
}
echo $result;
}
?>
Here is the HTML
<form role="form" method="post" action="<?php echo $url;?>">
<input type="checkbox" name="ans1" value="A">A
<input type="checkbox" name="ans2" value="B">B
<input type="checkbox" name="ans3" value="C">C
<input type="checkbox" name="ans4" value="D">D
<input type="submit" name="test" value="Submit Answer">
</form>

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) ) {
// ...
}

php function problem

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;
}

Categories