Jump to content

preg_replace = Search and Replace


SharkBait

Recommended Posts

I am trying to replace something within a block of text with something else and it works. But I would like to have it replace the text and leave it in the place it found it.

 

<?php
$str = "This is some text that I would like to display. There is a poll at the end of is [poll=3]";

$str = preg_replace("/\[poll=(\d+)\]/sie", "display_poll('\\1')", $str);

?>

 

When the code runs, it will replace [poll=3] with the proper code but it puts it at the beginning of the string and not where the [poll=3] is seen.

 

Am I doing something wrong? You can see an example here: http://www.tyleringram.com/blog/The-Real-Meaning-Of-Christmas the poll should actually be _after_ where it says 'I have also placed a poll here'

 

 

Link to comment
https://forums.phpfreaks.com/topic/81682-preg_replace-search-and-replace/
Share on other sites

<?php
function display_poll($poll_id = 0, $POLL_WIDTH = 300) {

if($poll_id == 0) {
	// No ID set to show latest poll
	$strqry = "SELECT id FROM blog_polls ORDER BY id DESC LIMIT 1;";
	$query = mysql_query($strqry) or die("MySQL Error: <br />{$strqry}<br />". mysql_error());
	$result = mysql_fetch_array($query, MYSQL_ASSOC);
	$poll_id = $result['id'];
}
$strqry = "SELECT * FROM blog_polls WHERE id = '{$poll_id}'";
$query = mysql_query($strqry) or die("MySQL Error: <br />{$strqry}<br />". mysql_error());
$poll_question = mysql_fetch_array($query, MYSQL_ASSOC);

$question = $poll_question['question'];
// Display Question (header of poll
echo "<div class=\"MyPoll\" style=\"width: {$POLL_WIDTH}px; border; 1px solid #000; padding: 5px;\">\n";
// Get Question for Poll
echo "<div style=\"text-align: center;\"><strong>{$question}</strong><br /></div>\n";

// Find out if user has answered poll
// Query to see if User's IP address has already voted
$strqry = "SELECT ip_address FROM blog_polls_answers WHERE ip_address = '{$_SERVER['REMOTE_ADDR']}' AND poll_id = '{$poll_id}'";
$query = mysql_query($strqry) or die("MySQL Error: <br />{$strqry} <br />". mysql_error());
if(mysql_num_rows($query) == 0 || $ADMIN) {
	// User has not voted (based on IP Address)
	// User has not voted yet based on their IP Addrss - Show them Voting Form

	// Get Options for Poll
	$strqry = "SELECT * FROM blog_polls_options WHERE poll_id = '{$poll_id}'";
	$query = mysql_query($strqry) or die("MySQL Error: <br />{$strqry}<br />". mysql_error());

	$i = 0;
	// Loop through options and create 2D array using Question as main index

	while($poll_questions = mysql_fetch_array($query, MYSQL_ASSOC)) {
		$poll_info[$poll_question['question']][$poll_questions['id']] = $poll_questions['choice'];
		$i++;
	}

	//print_r($poll_info);

	echo "<form action=\"{$_SERVER['PHP_SELF']}\" method=\"post\">\n";

	// Loop through the values in the Poll Info Array which are the Choices for the Poll Question
	foreach (array_values($poll_info) as $options) {
		// Need to loop through the options because they are stored in a 2D array
		foreach($options as $id => $option) {
			// Print out the choices in the form of radio buttons
			echo "<input type=\"radio\" name=\"poll_answer\" value=\"{$id}\"> {$option}<br />\n";
		}
	}
	echo "<br />\n";
	echo "<input type=\"hidden\" name=\"PollID\" value=\"{$poll_id}\" />\n";
	echo "<input type=\"hidden\" name=\"IPAddress\" value=\"{$_SERVER['REMOTE_ADDR']}\" />\n";
	echo "<div align=\"center\"><input type=\"submit\" name=\"PollVote\" value=\"Vote\" /></div>\n";

	echo "</form>";

} else {
	// User has voted - Show Results
	//Query to find out total votes for figuring out percentages
	$strqry = "SELECT COUNT(*) FROM blog_polls_answers WHERE poll_id = '{$poll_id}' GROUP BY poll_id";
	$query = mysql_query($strqry) or die("BLAH");
	$num_votes = mysql_fetch_array($query, MYSQL_ASSOC);

	// Query to find voting levels
	$strqry = "SELECT T1.poll_Id, T1.option_id,  T2.choice, COUNT(*) 
			FROM blog_polls_answers AS T1 
			LEFT JOIN blog_polls_options AS T2 
			ON(T1.option_id = T2.id) 
			WHERE T1.poll_id = T2.poll_id
			AND T1.poll_id = '{$poll_id}'
			GROUP BY option_id";
	$query = mysql_query($strqry) or die("MySQL Error: <br /> {$strqry} <br />". mysql_error());

	// Loop through count and display bar, percentage and choice
	while($votes = mysql_fetch_array($query, MYSQL_ASSOC)) {
		$count = $votes['COUNT(*)'];
		// Round to 2 decimals
		$percent = round(($count / $num_votes['COUNT(*)']) * 100, 2);
		$barWidth = 170 * ($percent / 100);
		// Show Result
		echo "<div style=\"width: 98%; font-size: 9pt; padding-top: 10px;\">";
		echo "<div style=\" background-image: url('/images/poll-bar.gif'); background-repeat: repeat-x; float: left; width: {$barWidth}px; margin-right: 5px;\"> </div> <strong>{$percent}%</strong><br />";
		echo "{$votes['choice']}<br />";
		echo "</div>\n";
	}
	echo "<hr />Total Votes: {$num_votes['COUNT(*)']} <br />\n";
}

echo "</div><br />\n";
}
?>

preg_replace replaces whatever it found by whatever the function returns. Since the function is echoing things, those come first.

 

For example:

 

<pre>
<?php
$str = 'ABC';
echo $str = preg_replace('/C/e', 'example("\1")', $str);
function example ($matches) {
	echo 'Z';
}
?>
</pre>

 

The order is:

 

1. Set $str to ABC.

2. Call preg_replace.

3. Call example.

4. Echo Z.

5. Replace C with the return value (nothing).

6. Echo the result AB.

7. Final result: ZAB.

Ok if i use a While() loop would replace it as it finds it?

 

 

<?php

$code = "/\[poll=(\d+)\]/ise";
$replace = "display_poll('\\1')";

while(preg_match($code, $replace) {
  $str = preg_replace($code, $replace, $str);
}

?>

 

I use something similar when I want to replace

with <div class="quote"></div>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.