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
Related
This question already has answers here:
concat a for loop - php
(3 answers)
Closed 2 years ago.
Am writing some content to a file, I store all the content in a variable. Some parts of the file content need to be repeated with some minor changes, those changes are stored in a variable and I need to run a for loop for that change.
See the following code sample,
$looped_valueArray; //this is an array i need to loop the content in $looped_value
//to show all the values
$content = 'sample content '. $looped_value.'
fdgdf';
I could not loop write a forloop appending to a string like
$content = 'sample content '.
foreach($looped_valueArray as $looped_value) $looped_value;.'fdgdf';
Hi follow this scripts if you would like append your content in a variable:
$content ="sample content ";
foreach($looped_valueArray as $looped_value){
$content .=$looped_value;
}
You can't use a loop directly in the string. Either define a separate function that loops through the values, or, in the above example, you could just use implode():
$content = 'sample content ' . implode("", $looped_valueArray) . 'fdgdf';
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));
I'm pretty new to PHP so please bear with me for this one.
I have an array with emoticons, and I want to replace the emoticon text with the correct image, all within a for loop. So I'm trying to take my text variable and do a str_replace, but I'm not sure exactly how to display the text after the emoticons have been changed.
Here is my code:
$content = ":D Here is a sample sentence for this example :)";
$emotes = array(
[":)","<img class='emoticon' src='smile.png'>"],
[":D","<img class='emoticon' src='grin.png'>"],
);
for($i=0;$i<count($emotes);$i++) {
$contentWithEmotes = str_replace($emotes[$i][0], $emotes[$i][1], $content);
}
print $contentWithEmotes;
The problem this this is that it only displays the last image from the array, when I want it to display both of them.
How should I go about displaying the content with the correct image?
Thanks in advance for any help.
Restructure your array like this:
$emotes = [
":)"=>"<img class='emoticon' src='smile.png' />",
":D"=>"<img class='emoticon' src=grin.png' />"
];
Then use strtr:
$contentWithEmotes = strtr($content,$emotes);
Each time through the loop you need to process the result of the previous time, not the original content.
$contentWithEmotes = $content;
foreach ($emotes as $emote) {
$contentWithEmotes = str_replace($emote[0], $emote[1], $contentWithEmotes);
}
However, the strtr() solution is better.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to parse and process HTML with PHP?
Let's say I want to extract a certain number/text from a table from here: http://www.fifa.com/associations/association=chn/ranking/gender=m/index.html
I want to get the first number on the right table td under FIFA Ranking position. That would be 88 right now. Upon inspection, it is <td class="c">88</td>.
How would I use PHP to extract the info from said webpage?
edit: I am told JQuery/JavaScript it is for this... better suited
This could probably be prettier, but it'd go something like:
<?php
$page = file_get_contents("http://www.fifa.com/associations/association=chn/ranking/gender=m/index.html");
preg_match('/<td class="c">[0-9]*</td>/',$page,$matches);
foreach($matches as $match){
echo str_replace(array( "/<td class=\"c\">", "</td>"), "", $match);
}
?>
I've never done anything like this before with PHP, so it may not work.
If you can work your magic after page load, you can use JavaScript/JQuery
<script type='text/javascript'>
var arr = [];
jQuery('table td.c').each(
arr[] = jQuery(this).html();
);
return arr;
</script>
Also, sorry for deleting my comment. You weren't specific as to what needed to be done, so I initially though jQuery would better fit your needs, but then I thought "Maybe you want to get the page content before an HTML page is loaded".
Try http://simplehtmldom.sourceforge.net/,
$html = file_get_html('http://www.google.com/');
echo $html->find('div.rankings', 0)->find('table', 0)->find('tr',0)->find('td.c',0)->plaintext;
This is untested, just looking at the source. I'm sure you could target it faster.
In fact,
echo $html->find('div.rankings', 0)->find('td.c',0)->plaintext;
should work.
Using DOMDocument, which should be pre-loaded with your PHP installation:
$dom = new DOMDocument();
$dom->loadHTML(file_get_contents("http://www.example.com/file.html"));
$xpath = new DOMXPath($dom);
$cell = $xpath->query("//td[#class='c']")->item(0);
if( $cell) {
$number = intval(trim($cell->textContent));
// do stuff
}
I'm making a website and a PHPBB3 forum. I want the messages that are posted on the forum to show up on the main page of the website. I have gotten this concept down, except that the bbcode parsing is weird (phpbb3 adds a UID after each bbcode tag) and my bbcode parser does not include this. Since the UID is different for each post, I'm trying to get the PHP code to parse and remove this via MYSQL.
$query = #mysql_query("SELECT * FROM phpbb_posts where forum_id = 2;") or die (mysql_error());
$uid = $row['bbcode_uid'];
$content = $row['post_text'];
$content = str_replace($uid, '', $content);
$content = BBCode2html($content);
echo $content;
Is there a way I could replace the UID (bbcode looks like [u:1h77z1wc]UNDERLINED[/u:1h77z1wc] instead of [u]UNDERLINED[/u])?
You could replace it with a regex...
preg_replace('/\[((\w+)(:\w+))](.*?)\[\/\1]/s', '[$2]$4[/$2]', $str);
The following regular expression should do the trick:
preg_replace( '/\[(\/?[^:]+):[^\]]+\]/', '[$1]', $str );