Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Latest Edit:
Well, I came up with fairly "reliable" :) solution in form of a (portable) function, but since some ppl here got irked enough by not understanding the problem and blocked this question (a military solution: kill what you do not understand), I cannot post it here. Pity.
I have a set of files, which contain constants, like below.
define ('LNG_GSU_LNK_LBL', '[details]');
define( 'LNG_METHODCROSS_GSU_CLS' ,'class');
define('GSU_METH' , 'method');
define ( 'CROSS_GSU_ACTION_NO_REMOVE', 'cannot remove \' module \'(is); deployed');
What would be most reliable method to retrieve constant names and values from given, selected file.
EDIT:
I need to get these constants into array, without defining them actually, directly by reading file, e.g.:
array('LNG_GSU_LNK_LBL'=>'[details]','LNG_METHODCROSS_GSU_CLS'=> 'class')
... etc
EDIT 2:
So far I got this far:
$file_array = file($path, FILE_SKIP_EMPTY_LINES);
//implode lang file into a string removing php tags
$string1 = implode('', $file_array);
$string2 = str_replace(array(''), '', $string1);
//regex removing content between markers
$regex = '/\/\*.+?\*\//si';
$replace_with = '';
$replace_where = $string2;
$string3 = preg_replace($regex, $replace_with, $replace_where);
//regex: remove multiple newlines
$string4 = preg_replace("/\n+/", "\n", $string3);
EDIT 3:
expected result
array (
'LNG_GSU_LNK_LBL' => '[details]',
'LNG_METHODCROSS_GSU_CLS' => 'class',
'GSU_METH' => 'method',
'CROSS_GSU_ACTION_NO_REMOVE' => 'cannot remove \' module \'(is); deployed'
);
If you dont want to include the file, then you should use: token_get_all().
Otherwise, you should require/include the file containing them and you can iteratively use get_defined_constants():
$all = array();
$consts = get_defined_constants();
foreach($consts as $k=>$v){
if (strpos($k,"LNG")===0 && !isset($all[$k]))
$all[$k]=$v;
}
Note that parsing php source code is like parsing HTML with regex, better bet avoid it.
Building on dynamic's answer, include the file within another, separate, web accessible file, that is not loaded within your current application (so will have no other user defined constants at run time):
//standalone.php
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
echo json_encode($newUserConsts);
//within your application
$newUserConsts = json_decode(file_get_contents('http://yoursite.com/standalone.php'));
Or if you cant make a separate web accessible file:
$consts = get_defined_constants(true);
$existingUserConsts = $consts['user'];
include "that_file.php";
$consts = get_defined_constants(true);
$newUserConsts = $consts['user'];
var_dump(array_diff_key($newUserConsts, $existingUserConsts));
Related
This question already has answers here:
Parse Wordpress like Shortcode
(7 answers)
Closed 4 years ago.
I'm using str_replace to replace a simple shortcode which works fine:
$content = "[old_shortcode]";
$old_shortcode = "[old_shortcode]";
$new_shortcode = "[new_shortcode]";
echo str_replace($old_shortcode, $new_shortcode, $content);
However I want to also replace attributes inside the shortcode without affecting any text content, for example change this:
[old_shortcode old_option_1="Text Content" old_option_2="Text Content"]
To this:
[new_shortcode new_option_1="Text Content" new_option_2="Text Content"]
Much appreciated if anyone could advise on how to do this.
To clarify, this question is not about parsing a shortcode (as it has been marked as a duplicated), it's about replacing one shortcode with another which the duplicate question linked to does not answer.
Edit:
I figured it out myself, however it's probably not a very elagant solution if anyone wants to suggest something better?
$pattern1 = '#\[shortcode(.*)attribute1="([^"]*)"(.*)\]#i';
$replace1 = '[shortcode$1attribute1_new="$2"$3]';
$pattern2 = '#\[shortcode(.*)attribute2="([^"]*)"(.*)\]#i';
$replace2 = '[shortcode$1attribute2_new="$2"$3]';
$pattern3 = '#\[shortcode(.*)(.*?)\[/shortcode\]#i';
$replace3 = '[new_shortcode$1[/new_shortcode]';
$content = '[shortcode attribute2="yes" attribute1="whatever"]Test[/shortcode]';
echo preg_replace(array($pattern1,$pattern2,$pattern3), array($replace1,$replace2,$replace3), $content);
Use preg_replace() instead that select only part of string you want using regex.
$newContent = preg_replace("/[a-zA-Z]+(_[^\s]+)/", "new$1", $content);
Check result in demo
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Well I am trying to make a simple php system.
Anywise I need to separate the text when I want to add it to the database.
So for example I want to add:
abc:123
I want that the : will be the separater, so it'll look like this:
abc
123
And then both will go to a different table.
Could someone help me with this? As I am not an experience PHP coder, yet I am willing to learn how to do this.
Kind regards
This is pretty basic stuff..
$data = explode(':','abc:123');
foreach($data as $word)
{
// some code here
}
Use Split:
<?php
$data = "abc:123";
list ($var1, $var2) = split (':', $data);
echo "Var1: $var1; Var2: $var2;<br />\n";
?>
You can achieve this using explode.
abc:123
Is a string. Let's define it as a variable:
$origin = "abc:123";
You can split the string, using : as the separator.
$separator = ":";
$exploded = explode($separator, $origin);
Now you have an array which you can use to access abc and 123 individually.
$pre = $exploded[0];
$post = $exploded[1];
You don't know how many splits there will be?
That's okay. Your array simply increases, meaning you can simply loop through the array and handle the values.
foreach ($exploded as $split)
{
// Do something with $split
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am totally new to PHP development and I would like to extract the contents of a meta tag.
I have this code that allows me to extract the contents of the element # squad.
// Pull in PHP Simple HTML DOM Parser
include("simplehtmldom/simple_html_dom.php");
// Settings on top
$sitesToCheck = array(
// id is the page ID for selector
array("url" => "http://www.arsenal.com/first-team/players", "selector" => "#squad"),
array("url" => "http://www.liverpoolfc.tv/news", "selector" => "ul[style='height:400px;']")
);
$savePath = "cachedPages/";
$emailContent = "";
// For every page to check...
foreach($sitesToCheck as $site) {
$url = $site["url"];
// Calculate the cachedPage name, set oldContent = "";
$fileName = md5($url);
$oldContent = "";
// Get the URL's current page content
$html = file_get_html($url);
// Find content by querying with a selector, just like a selector engine!
foreach($html->find($site["selector"]) as $element) {
$currentContent = $element->plaintext;;
}
// If a cached file exists
if(file_exists($savePath.$fileName)) {
// Retrieve the old content
$oldContent = file_get_contents($savePath.$fileName);
}
// If different, notify!
if($oldContent && $currentContent != $oldContent) {
// Build simple email content
$emailContent = "Hey, the following page has changed!\n\n".$url."\n\n";
}
// Save new content
file_put_contents($savePath.$fileName,$currentContent);
}
// Send the email if there's content!
if($emailContent) {
// Sendmail!
mail("me#myself.name","Sites Have Changed!",$emailContent,"From: alerts#myself.name","\r\n");
// Debug
echo $emailContent;
}
But I want to change this code to get the number of comments in income.
Here is the meta tag where i would just extract the number of comments :
<meta item="desc" content="Comments:645">
Am I clear enough, do you understand me?
If I am not explicit enough, ask me?
Thanks for help
There's two ways to do this. You could either use the native PHP function: get_meta_tags() like so:
$tags = get_meta_tags('http://yoursite.com');
$comments = $tags['desc'];
Or you could use RegEx, but the above would be much more practical.
What you are looking for might be screen scraping.
This is the process where a programming-language like php, python or ruby loads a website in memory and uses various selectors to grab content from it.
Screen scraping is mostly used on websites that feature a lot of interesting data but have no json or xml API's
having googled around for it I stumbled on this post:
PHP equivalent of PyQuery or Nokogiri?
This article explains more about screen-scraping for web:
http://en.wikipedia.org/wiki/Web_scraping
Look for use domDocument
$dom = new domDocument;
$dom->loadHTML($htmlPage);
$metas = $dom->documentElement->getElementsByTagName('meta');
$ar = array();
foreach ($metas as $meta) {
$name = $meta->getAttribute('name');
$value = $meta->getAttribute('content');
$ar[$name] = $value;
}
print_r($ar); // print array meta-values
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the program below
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
$fileName = "file.php"
$fp = fopen($fileName,'w');
$msg = $array;
fwrite($fp,$msg);
fclose($fp);
In this file "file.php", i want to write an array...such tha its read like
<?
$array[name1][0] = 'name';
$array[name1][1] = '11';
$array[name2][0] = 'name2';
$array[name2][1] = '11';
but it's not working.
Use json_encode or serialize to get a storable (and compact) representation of your data structure, then json_decode or unserialize to get it back.
The var_export function does just that:
fprintf($fp, '<?php $array = %s;', var_export($array, true));
It generates valid PHP code and you can include the file after that:
include "file.php";
Note that you can return from a PHP file, so this would work too:
fprintf($fp, '<?php return %s;', var_export($array, true));
And then:
$array = include "file.php";
Alternatives to generating PHP code are json_encode/json_decode, or serialize/unserialize.
You can do it like this:
fwrite($fp,print_r($msg,true));
If you want to be able to read the file later and get an PHP array back, then you need to "serialize" the array:
and later
$array = unserialize(file_get_contents("test.data"));
if it should look readable in the file, you var_export($array,1) or print_r($array,1) and store their output.
The closest you're going to get, natively, is by using var_export and writing its return value to the file.
Failing that, you should implement something to build that format from an Array.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have an array of keys and a medium/long string.
I need to replace only max 2 keys that I found in this text with the same keys wrapped with a link.
Thanks.
ex.:
$aKeys = array();
$aKeys[] = "beautiful";
$aKeys[] = "text";
$aKeys[] = "awesome";
...
$aLink = array();
$aLink[] = "http://www.domain1.com";
$aLink[] = "http://www.domain2.com";
$myText = "This is my beautiful awesome text";
should became "This is my <a href='http://www.domain1.com'>beautiful</a> awesome <a href='http://www.domain2.com'>text</a>";
Don't really understood what you need but you can do something like:
$aText = explode(" ", $myText);
$iUsedDomain = 0;
foreach($aText as $sWord){
if(in_array($sWord, $aKeys) and $iUsedDomain < 2){
echo "<a href='".$aLink[$iUsedDomain++]."'>".$sWord."</a> ";
}
else{ echo $sWord." "; }
}
So, you could use a snippet like this. I recommend you to update this code by using clean classes instead of stuff like global - just used this to show you how you could solve this with less code.
// 2 is the number of allowed replacements
echo preg_replace_callback('!('.implode('|', $aKeys).')!', 'yourCallbackFunction', $myText, 2);
function yourCallbackFunction ($matches)
{
// Get the link array defined outside of this function (NOT recommended)
global $aLink;
// Buffer the url
$url = $aLink[0];
// Do this to reset the indexes of your aray
unset($aLink[0]);
$aLink = array_merge($aLink);
// Do the replace
return ''.$matches[1].'';
}