Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDarrell Conklin
Python Development Techdegree Student 22,377 PointsFind part of a string inside of a variable.
I'm trying to find a function that will check / search for a value inside of a string inside of a variable. Similar to in_array().
1 Answer
Matthew Carson
5,965 PointsDo you mean like strpos()?
It returns the index of a searched string, or false if the searched string isn't found.
Say I wanted to find 'York' inside of 'New York'
<?php
$string = 'New York';
$find = 'York';
strpos($string, $find); // Would return 4
echo strpos($string, $find) ? 'Found it!' : 'Did not find it.'; // Would echo 'Found it!'
Is this what you mean?
Darrell Conklin
Python Development Techdegree Student 22,377 PointsYes that is what I was wanting to do.
Darrell Conklin
Python Development Techdegree Student 22,377 PointsI ended up doing something like this:
<?php
$find = "Full DOB available and matched input";
$test = strpos($response, $find);
if ($test) {
echo "You have passed age verification.";
} else {
echo "You have failed age verification";
}
?>
I don't really understand what is going on here:
<?php
echo strpos($string, $find) ? 'Found it!' : 'Did not find it.'; // Would echo 'Found it!'
?>
I'm assuming that is some shorthand syntax for testing if the expression is true?
Darrell Conklin
Python Development Techdegree Student 22,377 PointsDarrell Conklin
Python Development Techdegree Student 22,377 PointsIf it even exists and if not then how would I go about doing something like that.