John Davidson

php - Find term with asterisk *


I have a big string with html:

$html = '...hello{"text":"52"},{"text":" watching"}world...';

I want to search in $html with:

{"text":"*"},{"text":" watching"}

So I can get the number (where the asterisk is)? In my example, it is 52, but it can be any number.

I should end up with $number equal 52. Is regex the appropriate route?

My Answer:
To find a term with an asterisk in a big string with HTML using PHP, you can use regular expressions. Here's an example code snippet that demonstrates how to achieve this:

$html = '...hello{...*__world...}';

// Define the regular expression pattern to match the term with an asterisk and two underscores
$pattern = '/\*\_\_([^\s\{\}]+)/';

// Perform a regular expression match
if (preg_match($pattern, $html, $matches)) {
// The matched term is stored in $matches[1]
$matchedTerm = $matches[1];
echo "Term with asterisk and two underscores: " . $matchedTerm;
} else {
echo "No match found.";

In this code snippet, the regular expression pattern `/\*\_\_([^\s\{\}]+)/` is used to match a term that starts with an asterisk followed by two underscores and captures the term that follows it. The `preg_match` function is then used to perform the regular expression match on the HTML string. If a match is found, the matched term is stored in the `$matches` array and then printed out. If no match is found, a message indicating that no match was found is displayed.

Rate this post

3 of 5 based on 8031 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us