Does a star need to be inside a galaxy?

No, stars do not need to be inside a galaxy. It is estimated that about 10% of stars do not belong to a galaxy [1]. While most intergalactic stars formed inside a galaxy and were ejected by gravitational interactions, stars can form outside of galaxies as well [2].

We assume that such stars could have planets, just like stars in a galaxy, although no specific examples have been detected yet.

[1] "Detection of intergalactic red-giant-branch stars in the Virgo cluster", Ferguson et al. Nature 391.6666 (1998): 461.

[2] "Polychromatic view of intergalactic star formation in NGC 5291", M. Boquien et al. A&A, 467 1 (2007) 93-106.